Si des fois vous avez un doute sur le type d’une variable vous pouvez utiliser typeid.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <typeinfo>
 
using namespace std;
 
int main(void)
{
  // built-in types:                                                            
  int i;
  int * pi;
  cout << "int is: " << typeid(int).name() << endl;
  cout << "  i is: " << typeid(i).name() << endl;
  cout << " pi is: " << typeid(pi).name() << endl;
  cout << "*pi is: " << typeid(*pi).name() << endl;
  cout << "&pi is: " << typeid(&pi).name() << endl << endl;
  return (0);
}

L’instruction typeid affiche une information cryptique du genre:

int is: i
i is: i
pi is: Pi
*pi is: i
&pi is: PPi

Il faut comprendre i Integer, Pi Pointer to Integer et PPi Pointer to Pointer to Integer.

Là où cela devient plus fun c’est avec des classes/structures

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <typeinfo>
 
using namespace std;
 
struct Base {};
struct Derived : Base {};
struct Poly_Base {virtual void Member(){}};
struct Poly_Derived: Poly_Base {};
 
int main(void)
{
  Derived derived;
  Base* pbase = &derived;
  cout << "derived is: " << typeid(derived).name() << endl;
  cout << " *pbase is: " << typeid(*pbase).name() << endl;
  cout << boolalpha << "same type? ";
  cout << ( typeid(derived)==typeid(*pbase) ) << endl << endl;
 
  Poly_Derived polyderived;
  Poly_Base* ppolybase = &polyderived;
  cout << "polyderived is: " << typeid(polyderived).name() << endl;
  cout << " *ppolybase is: " << typeid(*ppolybase).name() << endl;
  cout << boolalpha << "same type? ";
  cout << ( typeid(polyderived)==typeid(*ppolybase) ) << endl << endl;
 
  return (0);
}

Donne:

derived is: 7Derived
*pbase is: 4Base
same type? false

polyderived is: 12Poly_Derived
*ppolybase is: 12Poly_Derived
same type? true

Vous pouvez supprimer le virtual devant la méthode Member() (c’est valide en C++). L’identification n’est plus la même.

Source (surtout les exemples, j’avais pas envie de les refaire): CPlusPlus.com – typeinfo