【发布时间】:2017-08-16 13:40:35
【问题描述】:
我正在尝试在 C++ 中创建一个以 string 为键的 map 和一个作为 value 的通用方法,但我不知道这是否可能。我想做这样的事情:
void foo(int x, int y)
{
//do something
}
void bar(std::string x, int y, int z)
{
//do something
}
void main()
{
std::map<std::string, "Any Method"> map;
map["foo"] = &foo; //store the methods in the map
map["bar"] = &bar;
map["foo"](1, 2); //call them with parameters I get at runtime
map["bar"]("Hello", 1, 2);
}
这可能吗?如果是,我怎么能意识到这一点?
【问题讨论】:
-
然后您可以阅读文档。
&foo和&bar是不同的类型。第一种是(void *)(int, int),第二种是(void *)(std::string, int, int)。所以你需要有不同的想法。 -
顺便说一句,你最初的任务是什么?
-
当您尝试致电
map["foo"]("Hello")时会发生什么? -
也许你应该看看here
-
@suraznegi 这很不安全...
标签: c++