Using the C++ typeid operator, type_info::name() member functions

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Demonstrating the use of the C++ typeid operator, type_info::before() and type_info::name() methods

To show: Using typeid operator, type_info::before() and type_info::name() member functions

 

 

// Using typeid operator, type_info::before() and type_info::name() member functions

#include <iostream>

#include <typeinfo>

using namespace std;

 

// T - True, F - False

#define T 1

#define F 0

 

// a base class

class A { };

 

// a derived class

class B : A { };

 

int main(void)

{

char c = ' ';

float f = 0.00;

 

// using typeinfo operator, == for comparison

if (typeid(c) == typeid(f))

cout<<"c and f are the same type."<<endl;

else

cout<<"c and f are different type."<<endl;

 

// using true and false comparison...

// name() and before() are typeinfo member functions...

cout<<typeid(int).name();

cout<<" before "<<typeid(double).name()<<": "<<

(typeid(int).before(typeid(double)) ? T:F)<<endl;

cout<<typeid(double).name();

cout<<" before "<<typeid(int).name()<<": "<<

(typeid(double).before(typeid(int)) ? T:F)<<endl;

cout<<typeid(A).name();

cout<<" before "<<typeid(B).name()<<": "<<

(typeid(A).before(typeid(B)) ? T:F)<<endl;

 

return 0;

}

 

Output example:

 

c and f are different type.

int before double: 1

double before int: 0

class A before class B: 1

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index