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
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.
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.
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.
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.
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++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With