Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define a macro/typedef/etc for tr1::unordered_map that doesn't bind the template arguments?

This might be a little silly question, but I just have to ask it. I am trying to use the unordered_map class in C++, but instead of referencing it everytime as tr1::unordered_map, I would like to just use the keyword hashMap.I know that

typedef tr1::unordered_map<string, int> hashMap 

works but that kind of fixes the datatype of the key and the value corresponding to the hashMap whereas I would like to have more like the following:

#define hashMap tr1::unordered_map

where I can just define the datatype of the key and the value depending on the the requirement, but this does not work. Did anyone face this problem before?

Thanks

like image 535
Vinayak Agarwal Avatar asked Feb 21 '23 06:02

Vinayak Agarwal


2 Answers

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

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

A usual workaround for C++03 is to make 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;

Inheriting from the class is possible in theory, but usually users refrain from doing so since the STL classes weren't meant to be inherited from.

like image 132
Philipp Avatar answered Apr 28 '23 02:04

Philipp


One possibility would be to use inheritance to forward the key/value pair to unordered_map through a templated hashMap derrived class. IE:

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

Then you can use hashMap as a template but actually be using unordered_map's public interface.

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

Just don't do anything fancy other than forward, as STL types don't have virtual destructors.

like image 37
Doug T. Avatar answered Apr 28 '23 03:04

Doug T.