我首先有一个有效的简单示例(我第一次使用地图)。名称-值对的类型分别是指向函数指针的字符串。
#include <iostream>
#include <map>
using std::cout;
int foo() {
return 243;
}
int main() {
std::map<std::string, int (*)()> list;
list["a"] = foo;
cout << list["a"](); // 243
}
然后我尝试使用模板来指定类型。它在地图实例化中所说int
的地方是我想使用模板指定类型的地方。所以我尝试了,但我不知道在哪里放置<int>
我调用函数或制作名称-值对的位置。这是我尝试过的:
#include <iostream>
#include <map>
using std::cout;
int foo() {
return 243;
}
int main() {
template <typename N>
std::map<std::string, N (*)()> list;
list["A"] = <int> foo; // right here where you see <int>
cout << list["A"]();
}
这不起作用,因为我认为我没有放在<int>
正确的位置。我得到的错误是:
/tmp/134535385811595.cpp: In function 'int main()':
/tmp/134535385811595.cpp:11: error: expected primary-expression before 'template'
/tmp/134535385811595.cpp:11: error: expected `;' before 'template'
/tmp/134535385811595.cpp:14: error: 'list' was not declared in this scope
/tmp/134535385811595.cpp:14: error: expected primary-expression before '<' token
/tmp/134535385811595.cpp:14: error: 'N' was not declared in this scope
任何人都可以帮忙吗?