Re: rtti
Chameleon wrote:
Hi!
I have derived classes `Angle`, `Azimuth`, `Distance`, `Height` from
base class `Relation`.
I want to put all of these in a `vector<Relation>` but they have
different size, so, I create a `union AnyRelation` and I put all of
derived classes inside this union, and the vector become
`vector<AnyRelation>`.
When I want to check what type the derived class is, I use `typeid`.
typeid won't help you, as you must not access any member of a union
except for the one you put into the union. So typeid would enable you to
store a fixed set of types in a predefined union. (Anything else would
be an exception.) But how do you extract the classes from the union
without accessing the wrong one?
Is there a better approach, or I am going right?
Absolutely. If you really need polymorphic members in a vector, you
won't come around using pointer or smart pointers and separate allocations.
If you are restricted to only a few types, have a look at
boost::variant. It addresses almost exactly what you want to do.
Another try, is to put every derived class in its own vector:
vector<Azimuth>
vector<Angle>
vector<Distance>
and so on.
and in a `vector<Relation>` I can use references to real objects.
With this approach I can avoid the `typeid` because I can check if
pointer of derived class object belongs to a specific `vector`.
I would prefer to use a vector<Relation> that owns it's objects in some
way (shared or not).
And a final question:
Its better to create my own rtti, or to use build-in? (for speed)
My own rtti:
------------
class A {
A() : rtti(0) {}
int rtti;
int getRTTI() { return rtti; }
bool isB() { return rtti == 1; }
virtual ~A() {}
};
class B : public A {
B() { rtti = 1; }
};
This will primarily create a memory overhead, since unlike you almost no
compiler stores any RTTI per instance. As long as you use RTTI only for
equality comparison it is most likely faster than anything you could
write, because effectively only slots of the vtable are compared. There
is no virtual function call and no linear memory overhead.
Marcel