我想知道是否有一种方法可以使地图(在C ++中)返回一个函数。这是我的代码,它不起作用,我收到编译错误。
#include <map>
#include <iostream>
#include <string>
using namespace std;
map<string, void()> commands;
void method()
{
cout << "IT WORKED!";
}
void Program::Run()
{
commands["a"]();
}
Program::Program()
{
commands["a"] = method;
Run();
}
任何建议都会很棒!提前谢谢。
答案 0 :(得分:4)
您无法在地图中存储函数 - 只能指向函数的指针。清理了一些其他小细节后,您会得到类似的结果:
#include <map>
#include <iostream>
#include <string>
std::map<std::string, void(*)()> commands;
void method() {
std::cout << "IT WORKED!";
}
void Run() {
commands["a"]();
}
int main(){
commands["a"] = method;
Run();
}
至少在g ++ 4.7.1中,这会打印IT WORKED!
,因为你显然想要/期望。
答案 1 :(得分:2)
再次typedef
是你的朋友。
typedef void (*func)();
map<string, func> commands;