Explicit type identifier vs RTTI

Is there any advantage of using your own type identifier over RTTI?

eg.

class A { virtual int mytype() = 0; };
class B : public A { int mytype() {return 1;} };
class C : public A { int mytype() {return 2;} };

Could it be faster? Less overhead? Or should you always use RTTI in this situation?

+5
source share
3 answers

Do not assume that RTTI will have more / less overhead than your solution before you test it .

You must try both solutions and measure performance to get a reliable answer.

, -, "" , . , , dynamic_cast<> ( , ).

, dynamic_cast<> , .

: , "" , dynamic_cast<>.

+6

( ) :

  • .
  • , , A->B->D. , A *p = new D;, B* p ( ).

. ,

  • RTTI ( , RTTI)
  • - RTTI, .

, , . .

struct Base {
  enum TYPES { _BASE, _D1, _D2, _D3 };
  const TYPES &myType;
  Base (TYPES) : myType(_BASE) {}
};

struct D1 : Base {
  D1 () : Base(_D1) {}
};
+5

http://en.wikibooks.org/wiki/C%2B%2B_Programming/RTTI

There are some restrictions for RTTI. First, RTTI can only be used with polymorphic types. This means that your classes must have at least one virtual function, either directly or through inheritance. Secondly, due to the additional information needed to store types, some compilers require a special switch to enable RTTI.

So, if you need it to work on classes without virtual functions, you will have to implement it yourself.

+3
source

All Articles