vinod
vinod

Reputation: 281

How to use typedef for a generic class in c++

I am trying to use unordered_map. But in some of the servers we don't have tr1 library. In those cases I want to use the map. So, I want to write a header file where I will use one of the following lines.

typedef tr1::unordered_map hashmap;
typedef map hashmap;

My Problem is I am using different types of maps here.

map<string, string>
map<string, int>
map <string, map<string,int>> ..etc

If I can use the typedef to alias map or unordered_map as hashmap, then I can use the map as hashmap<string, string> , hashmap<int, int> in the code.

Is there any way to do this or If there is any better way please suggest me.

Thanks Vinod

Upvotes: 12

Views: 2298

Answers (3)

SuperElectric
SuperElectric

Reputation: 18874

This will be possible in c++0x, but currently there's no support for aliasing unspecialized templates. See: https://en.wikipedia.org/wiki/C%2B%2B0x#Template_aliases

As a workaround, you could use a macro to stand in for the map type, i.e:

#ifdef HAVE_TR1
#include <tr1/unordered_map>
#define HASH_MAP std::tr1::unordered_map
#else
#include <map>
#define HASH_MAP std::map
#endif

On an unrelated note, I'd call the alias "ASSOC_MAP" or even just "MAP" instead of "HASH_MAP". The latter name makes it sound like you're using hashes, lulling the user into thinking that it has constant-time insertions and deletions, rather than O(log N).

Upvotes: 2

Mark B
Mark B

Reputation: 96241

C++98 and 03 don't offer support for template typedefs, but you could do that with C++0x.

In the earlier versions you can use a template struct that has a value typedef to do what you want:

template <typename T1, typename T2>
struct hashmap
{
    typedef std::map<T1, T2> type;
};

Do note that this was for illlustrative purpose and you might also need extra template parameters to cover the comparison operator and allocator.

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

You need to use a so-called metafunction for this:

template <typename Key, typename T>
struct hashmap {
    typedef std::unordered_map<Key, T> type;
    // or
    //typedef std::map<Key, T> type;
};

Which would be used like this:

hashmap<int, float>::type some_map;

This is a very common pattern. C++0x makes this somewhat easier by providing an improved using statement but for the moment this is the best there is.

Upvotes: 10

Related Questions