如何创建对象函数指针C++映射?
How do I create C++ map of object function pointers?
我正在尝试创建字符串到函数的映射。 当它是一个简单的函数时,我已经看到了如何做到这一点:
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) }
};
警告:编写但未编译的代码;可能存在错误。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- C++映射分割错误(核心转储)
- 内联映射初始化的动态atexit析构函数崩溃
- 使用"std::unordereded_map"映射到"std::list"对象
- 如何从多映射中删除特定的重复项
- 在未初始化映射的情况下,将值插入到映射的映射中
- QT通过C++添加映射QML项目
- 在c++中访问int到类对象的映射时出错
- 在C++中搜索嵌套多映射值
- 错误处理.将系统错误代码映射到泛型
- C++匿名结构作为std::映射值
- 如何从存储在std::映射中的std::集中删除元素
- 递归无序映射
- 正在VS调试器中监视映射条目