I have a class
that contains a map
. Earlier, there were two maps
, one with char
key and one with string
key. I created a class
that contains enum
and union
and two constructors, one from char
and one from string
, overloaded comparison operator and used that class
as key.
But I keep wondering. could this have been solved with clever use of inheritance instead?
edit:
My class is something along the lines:
class A
{
enum B
{
Ax, Ay
} b;
union C
{
X x;
Y y;
} c;
public:
A(X x) : b(Ax), c(x) {}
A(Y y) : b(Ay), c(y) {}
bool operator<(A& rhs)
{
if(this->b == rhs.b)
{
if(this->b == Ax) return this->c.x < b.c.x;
if(this->b == Ay) reutrn this->c.y < b.c.y;
}
// if the "type" is different, I assume values are different
// and all I need is any strong ordering, actual order doesn't matter
return this->b < rhs.b;
}
};
Later on I can use it fe. like that:
class Q
{
// ...
public:
Q(vector<A> v)
{
// don't worry about this code, I haven't figured out how c++11 for each
// works exactly yet, but it's not important, I can do that myself
for each (auto a in v)
{
// ...
}
}
};
Now using curly brackets I can initialize Q
with various A
, and I can create distinct A
from char
or string
.
My class, A
accomplished this by containing union for the actual data required to compare keys of one type, and enum used to compare keys of different types. Basic inheritance tree with virtual base class and two subclasses would result in every instance containing the same amount of information - different internal variables would take role of the union, and different actual classes would take the role of the enum. But I just can't come up with a way to do it properly without breaking any important principles.