How to define a macro / typedef / etc for tr1 :: unordered_map that does not bind template arguments?

This may be a bit of a dumb question, but I just have to ask about it. I am trying to use the unordered_map class in C ++, but instead of referring to it every time like tr1 :: unordered_map, I would just like to use the hashMap keyword. I know that

typedef tr1::unordered_map<string, int> hashMap 

works, but this type corrects the data type of the key and the value corresponding to hashMap, while I would like to have more like the following:

 #define hashMap tr1::unordered_map 

where I can simply determine the key data type and value depending on the requirement, but this does not work. Has anyone encountered this problem before?

thanks

+4
source share
2 answers

This is something that was not in C ++ before C ++ 11. In C ++ 11, you can use template using :

 template<typename Key, typename Value> using hashMap = tr1::unordered_map<Key, Value>; 

The usual workaround for C ++ 03 is to create a template structure with a type member:

 template<typename Key, typename Value> struct hashMap { typedef tr1::unordered_map<Key, Value> type; }; // then: hashMap<string, int>::type myMap; 

Inheritance from a class is possible in theory, but usually users abstain from this, since STL classes were not intended to be inherited.

+5
source

One possibility is to use inheritance to send the key / value pair to unordered_map through the hashMap derrived template class. IE:

 template<typename key, typename value> class hashMap : public tr1::unordered_map<key, value> { public: // Add constructors to forward to tr1::unordered_map constructors as // needed hashMap() : tr1::unordered_map<key, value>() {} //... }; 

Then you can use hashMap as a template, but actually use the unordered_map public interface.

 hashMap<string, int> foo; foo["bar"] = 5; 

Just do nothing unusual than direct, as STL types do not have virtual destructors.

+2
source

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


All Articles