Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef a template class without specifying the template parameters

I'm trying to typedef either an unordered_map or std::map depending whether there are TR1 libraries available. But I don't want to specify the template parameters. From what i've read so far, typedef'ing templates without arguments is not possible until official c++0x standard is available. So does anyone know an elegant workaround for this?

#ifdef _TR1 #include <unordered_map>  typedef std::tr1::unordered_map MyMap; //error C2976: too few template arguments #else #include <map>  typedef std::map MyMap; //error C2976: too few template arguments #endif 
like image 730
Rollin_s Avatar asked Sep 24 '09 22:09

Rollin_s


People also ask

Can a template be a template parameter?

Templates can be template parameters. In this case, they are called template parameters. The container adaptors std::stack, std::queue, and std::priority_queue use per default a std::deque to hold their arguments, but you can use a different container.

Which is correct example of template parameters?

For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.

What is a non-type template parameter?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.

How do you pass a parameter to a template in C++?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.


1 Answers

The way I've seen this done is to wrap the typedef in a template-struct:

template<typename KeyType, typename MappedType> struct myMap { #ifdef _TR1     typedef std::tr1::unordered_map<KeyType, MappedType> type; #else     typedef std::map<KeyType, MappedType> type; #endif }; 

Then in your code you invoke it like so:

myMap<key, value>::type myMapInstance; 

It may be a little more verbose than what you want, but I believe it meets the need given the current state of C++.

like image 145
fbrereto Avatar answered Sep 18 '22 06:09

fbrereto