David G
David G

Reputation: 96810

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

I first have this simple example that works (my first time using maps). The type of the name-value pairs is a string to a function pointer respectively.

#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

}

Then I tried using a template to specify the type. Where it says int in the map instantiation is where I'd like to specify the type using a template. So I tried but I don't exactly know where to put <int> where I'm either calling the function or making the name-value pairs. This is what I tried:

#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"]();

}

This doesn't work because I don't think I'm putting <int> in the right place. The errors I'm getting are:

/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

Can anyone help?

Upvotes: 0

Views: 72

Answers (1)

jrok
jrok

Reputation: 55395

template <typename N>
std::map<std::string, N (*)()> list;

template<typename> syntax is used for definitions of templates. Map class template is already defined elsewhere, you can only provide template parameters when you're instantiating it.

You can do what you want by wrapping your map in a class template:

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

and then instantiate and use it like:

int foo() { }

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

Upvotes: 3

Related Questions