我希望能够基于从文件中读取的数据来调用函数。
因此,对于每种项目类型,我想调用所需的reader方法。
我写了这段代码,但是无法在要向 map 添加函数指针的地方编译。怎么了?
#include <vector>
#include <map>
#include <iostream>
class reader
{
std::map< std::string, void(*)()> functionCallMap; // function pointer
void readA(){ std::cout << "reading A\n";};
void readB(){ std::cout << "reading B\n";};;
public:
reader()
{
*functionCallMap["A"] = &reader::readA;*
*functionCallMap["B"] = &reader::readB;*
}
void read()
{
auto (*f) = functionCallMap["A"];
(*f)();
}
};
我正在构造函数中填写 map 。
最佳答案
您可以将std::function
与lambda或std::bind
结合使用:
class reader
{
std::map<std::string, std::function<void()>> functionCallMap;
void readA() { std::cout << "reading A\n"; };
void readB() { std::cout << "reading B\n"; };
public:
reader()
{
functionCallMap["A"] = [this]() { readA(); };
functionCallMap["B"] = std::bind(&reader::readB, this);
}
void read()
{
functionCallMap["A"]();
functionCallMap["B"]();
}
};
关于c++ - 如何将方法作为函数指针存储在 map 容器中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53336880/