[C++] Ce face operatorul 'typeid'?

Despre limbajul de programare C++ si biblioteca standard STL (forum moderat)
Post Reply
User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi
Contact:

[C++] Ce face operatorul 'typeid'?

Post by Ovidiu Cucu » 10 Aug 2011, 14:59

Intrebare
Ce face operatorul typeid?

Raspuns
Operatorul typeid intoarce o referinta la un obiect tip const std::type_info ce permite identificarea tipului la run-time.

Exemple

Code: Select all

   if(typeid(x) == typeid(y))
   {
      std::cout << "x and y have the same type" << std::endl;
   }

Code: Select all

class CObject {/*...*/};
   //...
   if(typeid(x) == typeid(CObject))
   {
      std::cout << "x is of type class CObject" << std::endl;
   }

Code: Select all

   const type_info& ti = typeid(x);
   std::cout << "The type name of x is " << ti.name() << std::endl;

Code: Select all

template <class T> bool is_equal(T x, T y)
{
   const std::type_info& ti = typeid(T);
   std::cout << "compare " << ti.name() << " types" << std::endl;
   return x == y;
}

Code: Select all

#include <iostream>

class CBase
{
   virtual void f() {} 
};
class CFoo : public CBase{/*...*/};
class CBar : public CBase{/*...*/};

void DoSomething(CBase& rBase)
{
   std::cout << "Type: " << typeid(rBase).name() << std::endl; 
}

int main()
{
   CFoo foo;
   DoSomething(foo);
   CBar bar;
   DoSomething(bar);

   return 0;
}
Note
  1. In ultimul exemplu, clasa CBase este polimorfica (contine functii virtuale). Daca nu ar fi fost polimorfica atunci rezultatul ar fi indicat tipul 'class CBase' (static type, tipul parametrului rBase) si nu 'class CFoo' si respectiv 'class CBar' (dynamic type, tipul obiectului din clasa derivata la care refera/pointeaza rBase).
  2. Specificatorii const si volatile sunt ignorati de typeid
  3. Headerul <typeinfo>, in care se afla definitia clasei type_info, trebuie inclus inainte de folosirea operatorului typeid.
Resurse
<< Back to C++ Index



Post Reply