Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specialize hashmap template

I'm using the hash_map in C++ and want to supply a simplified type name for it:

The key type and hasher function are always the same.

stdext::hash_map<std::string, [MAPPED TYPE], CStringHasher>

However, I don't really want to write all this every time I declare a hash map which maps strings to type X.

  • Can I write a template or macro that simplifies this?

So the above declaration would look like:

template<typename T> StringHashmap = stdext::hash_map<std::string, T, CStringHasher>

StringHashmap<int> mapA; //Maps std::string to int
StringHashamp<bool> mapB; //Maps std::string to bool
like image 475
Kris Avatar asked Nov 19 '25 00:11

Kris


1 Answers

As others said, template aliases is the way to go if you can use C++0x:

template < typename MappedType >
using StringHashMap = stdext::hash_map< std::string, MappedType, CStringHasher >;

StringHashMap< int > mapA;
StringHashMap< bool > mapB;

(As @MSalters noted, if you have C++0x available, you should probably use std::unordered_map.)

Otherwise, you can still use the usual workaround, which is to define a class template containing a typedef:

template < typename MappedType >
struct StringHashMap
{
    typedef stdext::hash_map< std::string, MappedType, CStringHasher > type;
};

StringHashMap< int >::type mapA;
StringHashMap< bool >::type mapB;

A drawback with this solution (which have engendered many questions here on SO) is that you sometimes need to prefix StringHashMap< T >::type by the typename keyword in order to assert to the compiler that this name effectively denotes a type. I will not dwell on this subject in this answer, you can check out this FAQ, and especially the accepted answer, for more information. (Thanks to @sbi for evoking this matter.)

like image 103
Luc Touraille Avatar answered Nov 20 '25 14:11

Luc Touraille