0

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

#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

任何人都可以帮忙吗?

4

1 回答 1

3
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;
于 2012-08-19T12:32:14.843 回答