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