Re: rtti
On May 2, 5:03 am, Chameleon <cham_...@hotmail.com> wrote:
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`.
It is asking for difficulties. C++0x changed the union a bit but i
still dislike it.
Is there a better approach, or I am going right?
I suspect your way it won't work.
1) More common alternatives:
vector<boost::shared_ptr<Relation> >
vector<tr1::unique_ptr<Relation> >
2) Just
vector<Relation*>
works for those who do not want dependency on boost or C++0x
extensions. It is more error-prone when dealing with raw pointers so
enwrap it into something.
3) You can remove the exposed polymorphism by using pimpl idiom so
Relation becomes envelope class and `Angle`, `Azimuth`, `Distance`,
`Height` are its hidden internal variants of implementation. Then
vector<Relation> works fine.
Another try, is to put every derived class in its own vector:
vector<Azimuth>
vector<Angle>
vector<Distance>
and so on.
That loses polymorphism over common interface Relation and you will
have several containers to manage.
and in a `vector<Relation>` I can use references to real objects.
References can not be stored in vector. Also you should avoid storing
iterators or references or pointers to elements of vector. These get
invalid if you insert, erase or push_back into vector.
With this approach I can avoid the `typeid` because I can check if
pointer of derived class object belongs to a specific `vector`.
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; }
};
Nah ... avoid magic numbers and avoid writing things yourself that are
present in language. The people writing compilers are way over average
skilled and their user base is large so their defects will be most
likely discovered and fixed before your software reaches your end
users.
Use built-in RTTI when you need to. Beware that you should avoid
directly using RTTI as lot you can. Using RTTI too lot indicates weak
design. dynamic_cast can be useful for acquiring (or checking
presence of) other interfaces when having an interface pointer. For
typeid there are too few good use cases besides debugging and
troubleshooting.