C ++如何创建一个接收字符串并返回func的映射

时间:2012-10-23 03:00:57

标签: c++ function map func

我想知道是否有一种方法可以使地图(在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();
}

任何建议都会很棒!提前谢谢。

2 个答案:

答案 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;