如何指定与模板一起使用的地图类型

How do I specify the type of a map used with a template?

本文关键字:地图 类型 一起 何指定      更新时间:2023-10-16

我首先有这个简单的示例(我第一次使用地图)。名称/值对的类型分别是指向函数指针的字符串。

#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;