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.
Why not use
boost::variant
orstd::variant
once the latter becomes available in your compiler?It feels like the most natural solution to the problem and makes the code very readable:
Output:
Although generally you can simplify
union
code with inheritance, it does not help much when you need mixed group of objects to have behavior that is aware of all other implementations.You can make a base class, and have two subclasses - for string-based keys and for char-based keys. However, the comparison operator of string-based keys must know how to work with char-based keys, and the operator for char-based keys must know how to work with string-based keys. In situations like that the code becomes "monolithic", making a single class alternative more preferable.
In your situation, a class that exposes two constructors, and maintains a
string
internally should be an easy alternative: