gpt4 book ai didi

c++ - 如何指定与模板一起使用的 map 类型?

转载 作者:行者123 更新时间:2023-11-28 00:54:56 25 4
gpt4 key购买 nike

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

#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在 map 实例化中,我想使用模板指定类型。所以我试过了,但我不知道把<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>语法用于模板的定义。 map 类模板已经在别处定义,您只能在实例化时提供模板参数。

您可以通过将 map 包装在类模板中来做您想做的事:

template<typename ReturnType>
struct Wrapper {
std::map<std::string, ReturnType (*)()> m;
};

然后像这样实例化和使用它:

int foo() { }

Wrapper<int> w;
w.m["foo"] = foo;

关于c++ - 如何指定与模板一起使用的 map 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12026447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com