如何指定与模板一起使用的地图类型
How do I specify the type of a map used with a template?
我首先有这个简单的示例(我第一次使用地图)。名称/值对的类型分别是指向函数指针的字符串。
#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
谁能帮忙?
template <typename N>
std::map<std::string, N (*)()> list;
template<typename>
语法用于模板的定义。地图类模板已在其他地方定义,只能在实例化时提供模板参数。
您可以通过将地图包装在类模板中来执行所需的操作:
template<typename ReturnType>
struct Wrapper {
std::map<std::string, ReturnType (*)()> m;
};
然后实例化并像这样使用它:
int foo() { }
Wrapper<int> w;
w.m["foo"] = foo;
相关文章:
- CGAL:在浏览平面地图时使用类型"标记"
- C++以迭代方式搜索混合类型地图
- 为什么重建的地图类型与原始地图类型不同?
- 为什么我必须将地图值的类型从 & 更改为 (int*)&
- C++ 在地图中存储变体类型
- 如何高效/正确地存储等距游戏的不同类(单个超类的所有子类型)的地图?
- MPL地图实例化类型
- 具有可比的密钥类型的地图
- GCC shared_ptr和地图上make_shared分离的变量类型错误
- STLS STD :: MAP和STD :: vector;在地图中检查对象类型
- 来自存储在带有基类类型的地图中的派生类的调用函数
- 如何创建结构类型数组的地图对象
- 将自定义类型作为地图的可能键的可能方法有哪些
- 根据按键类型选择地图或unordered_map
- 推论具有不同值类型的地图的返回类型
- 如何以不同的数据类型作为值实现地图
- 如何从地图中的所有值类型中找到最大值
- 指针的地图指向不同返回类型和签名的功能
- 如何指定与模板一起使用的地图类型
- C++类似地图类型的模板专用化