Specialize hashmap template

I am using hash_map in C ++ and want to provide a simplified type name for it:

The key type and hash function are always the same.

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

However, I do not want to write all this every time I declare a hash map that displays lines for input X.

  • Is it possible to write a template or a macro that simplifies this?

So the above expression would look like this:

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
+3
source share
3 answers

As others have said, template aliases are 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, you should probably use one std::unordered_map.)

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

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

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

( SO) , StringHashMap< T >::type typename, , . , FAQ, , . ( @sbi .)

+5

++ (++ 03) . -

#define StringHashMap(type) stdext::hash_map<std::string, type, CStringHasher>

, , :

StringHashMap(pair<int, string>) myMap; // Error!

,

StringHashMap((pair<int), (string>)) myMap; // Error!

, . , . typedef, :

typedef pair<int, int> IntPair;
StringHashMap(IntPair) myMap; // Okay

++ 0x, , , :

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

, ++ 03 " typedef", , .

, ! templatetypedef, Stack Overflow, - ! .: -)

+2

Source: https://habr.com/ru/post/1791434/


All Articles