Joy
Joy

Reputation: 1777

why using a template as a parameter in the STL map template is refused?

I wrote this little code

std::map<int,template<class T>> map_;
map_.insert(make_pair<int,message>(myMsg.id,myMsg));

but the compiler doesn't seem to get it and displays as an error

template argument 2 is invalid

and when I tried to correct by doing this

template<class T>
std::map<int,T> map_;

it displays as an error :

expected primary-expression before 'template' |

error: expected ';' before 'template'

Upvotes: 1

Views: 20367

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409176

I'm not sure about this, but you are trying to declare a variable, and that definition has to be fully defined. Trying to use a template doesn't fully define the variable.

You can wrap it in a structure if you want to:

template<typename T>
struct Wrapper
{
    typedef std::map<int, T> map_type;
};

Then use it like this:

Wrapper<std::string>::map_type my_wrapped_map;
my_wrapped_map[1] = "Foo";

Upvotes: 6

user4333623
user4333623

Reputation: 1

define KEYINT_MAP(T) std::map<int, T>
KEYINT_MAP(class) map;

Upvotes: -1

Luchian Grigore
Luchian Grigore

Reputation: 258618

You're probably not using a C++11 compiler, and this line is invalid:

std::map<int,template<class T>> map_;

It should be

std::map<int,template<class T> > map_;

Notice the space between > >. Pre-C++11, >> is always treated as the bit shift operator.

Besides this, what is the code supposed to do? If I'm not mistaken, you should declare your map as

std::map<int,message> map_;

Now, std::map<int,template<class T>> map_; doesn't really make sense, unless this is a member of another template class, in which case you need

std::map<int,T> map_;

Upvotes: 1

Related Questions