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
As others said, template aliases is the way to go if you can use C++0x:
(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:
A drawback with this solution (which have engendered many questions here on SO) is that you sometimes need to prefix
StringHashMap< T >::typeby thetypenamekeyword 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.)