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.
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:
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.)
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