I have the following situation:
class A {
public:
int a;
// Just for RTTI
virtual ~A() = default;
}
class B : public A {
public:
int b;
}
And then I create an std::unordered_map<int, A>
, where I want to be able to store both A
s and B
s, and get back to their original representation.
I always know whether the element corresponds to an A
or a B
from context at the point of find()
by looking just at the key.
However, if I run the following program:
#include <unordered_map>
#include <iostream>
using namespace std;
class A {
public:
int a{};
A() = default;
A(int a) : a(a){}
// Just for RTTI
virtual ~A() = default;
};
class B : public A {
public:
B(int a, int b) : A(a), b(b) {}
int b;
};
int main()
{
std::unordered_map<int, A> m;
m[1] = A(4);
m[2] = B(2,5);
if (dynamic_cast<B *>(&m.at(2)) == nullptr) {
std::cout << "FAIL!" << std::endl;
}
}
I get a "FAIL" printed in my screen. This was not the behavior I expected; how can I get this to work?