26

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
Rollin_s
  • 1,983
  • 2
  • 18
  • 18
  • 1
    See this very close question : http://stackoverflow.com/questions/544842/c-typedef-ing-stl and the provided answers. Template typedefs are not valid C++ commands – Benoît Sep 24 '09 at 22:21
  • Very similar question: http://stackoverflow.com/questions/6907194/how-to-typedef-a-template-class It has another answer that's not mentioned here: "alias template" in c++11 – Jayesh Jul 31 '14 at 02:18

2 Answers2

38

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++.

fbrereto
  • 35,429
  • 19
  • 126
  • 178
  • 3
    It is indeed the usual way to simulate the lack of template typedefs in C++. However, I would have named the typedef "type" instead of "value", it seems more correct semantically speaking and it is more idiomatic. – Luc Touraille Sep 25 '09 at 12:13
4

You have to use full types for typedefs.

Use a #define macro instead.

ebo
  • 8,985
  • 3
  • 31
  • 37