如何创建对象函数指针C++映射?

How do I create C++ map of object function pointers?

本文关键字:C++ 映射 指针 函数 创建对象      更新时间:2023-10-16

我正在尝试创建字符串到函数的映射。 当它是一个简单的函数时,我已经看到了如何做到这一点:

typedef int (*GetIntFunction)(void);
int get_temp()
{
return 42;
}
map<string, GetIntFunction> get_integer_map { { "temp", &get_temp } };
auto iter = get_integer_map.find("temp");
int val = (*iter->second()();

但是,我希望我的函数指针指向特定对象的函数。 而且,我知道在创建地图时需要哪个对象。 像这样:

class TemperatureModel
{
public:
int GetTemp();
}
TemperatureModel *tempModel = new TemperatureModel();
map<string, GetIntFunction> get_integer_map { { "temp", &(tempModel->GetTemp} };

如果你想知道我为什么要这样做,我正在尝试从输入文件中读取参数列表,从正确的模型中获取它们的值,然后将其值输出到输出文件。 我还需要在运行时使用类似的映射设置值。

对于我们老式类型来说,最简单的方法是编写一个函数:

int call_it() {
return tempModel->GetTemp();
}

并将该函数存储在问题中的地图中:

map<string, GetIntFunction> get_integer_map {
{ "temp", call_it }
};

较新的方法是使用 lambda:

map<string, GetIntFunction> get_integer_map {
{ "temp", [=]() { return tempModel->GetTemp(); }
};

另一种方法(如 Kamil Cuk 的评论中所建议的(是使用std::function绑定对象和函数:

map<string, std::function<int()>> get_integer_map {
{ "temp", std::function<int()>(&TemperatureModel::GetTemp, tempModel) }
};

警告:编写但未编译的代码;可能存在错误。