The problem is: I want to use unordered_map to store keys and values, where the key can be either class A or class B, depending on the users options. Both classes A and B inherit from the same class P.
class A: public P {...}
class B: public P {...}
I would like to define the map with the abstract P class and later, depending on runtime options, assign there a map with A or with B as a key:
unordered_map< P, CValue, P::hash, P::equal_to> * pmap = new unordered_map< A, CValue, A::hash, A::equal_to>;
but I will get error:
cannot convert ... in initialization
How can I declare such a “virtual” map?
Here’s an example how you can make the map keyed on
P*but still use different implementations in the derived classes:The dynamic cast is valid because you promise only to compare pointers of the same derived type.
If you wanted to be cleaner, you could probably specialise
std::hash<P*>andstd::equal_to<P*>: