`

c++ -typeid operator

    博客分类:
  • c++
c++ 
阅读更多

typeid is the one of the meager offering of runtime type information hierarchy functionality. what it offers is the ability to determine at runtime the real type of an object (a pointer is a special type of variable, which we will lsee shorty in this post )

 

 

 

what is the typeid operator used for? 

 

it is used in advanced programming developement, when building debugger for example, or it is used to deal with persistent object through a pointer or a reference to a base class.

 

The program needs to find out the actual type of the object manipulated to list the properties of an object properly during a debugging session or to store and retrieve an object property 

 

During a debugging session or to store and retrieve an object property properly to find out the actual type of an object, the typeid operator can be used. 

 

 

For better describe what we will describe, here is the class hiearchy that we will use in this example. 

 

 

class employee 
{
};
class manager : public employee
{};

class programmer : public employee 
{
};

 

so, in the simplest case, what is the output of the followiong. 

 

 

void typeid_test() { 
	programmer obj ;
	programmer &re = obj;

	// we look at name() in the subsection on type_info 
	// below, name() returns the C-style string: "programmer"
	cout << typeid(re).name() << endl;
}

 

the typeid can accept two types of operand, one is an expression and the other is the name of the type. Let's first see the first type of operand (the later case will be covered in example later) . 

 

/**
* the operand of the typeid operator can be expression or type names of any type 
*
*/
void typeid_operand()
{
  int iobj;
  cout << typeid(iobj).name() << endl; // print : ints
  cout <<typeid(8.16).name() << endl; // prints : double
}

 when the oeprand to typeid operator is a class, but not a class of virtual function, the result of the typeid operator is well, not the type of underlying object.

 

 

/**
* if the typeid operand is a class type, but not of a class type with virtual functions. then the typeid operator indicates the type of 
* the operand is well, not the type of the underlying object
*/

class Base 
{
};
class Derived : public Base { };

void typeid_non_virtual_class() 
{
	Derived dobj;
	Base *pb = &dobj;

	cout << typeid(*pb).name() << endl; // prints : Base
}

 but, if the class does have virtual function, then the real derived object will be retrieved and its true type will be returned. 

 

/*
*  if the typeid oeprand is a class type , where if class to be examined is of virutal functions, then the 
* real derived classes will be returned.
*/
void typeid_result_virtual_class() 
{
	employee *pe = new manager();
	employee &re = *pe; 
	if (typeid(*pe) == typeid(manager)) cout << "typeid(*pe) == typeid(manager)" << endl; // true 
	if (typeid(re) == typeid(employee)) cout << "typeid(re) == typeid(employee)" << endl; // true 

	if (typeid(&re) == typeid(employee *)) cout << "typeid(&re) == typeid(employee *)" << endl;  // true 
	if (typeid(&re) == typeid(manager *)) cout << "typeid(&re) == typeid(manager *)" << endl; // false
}

 

you may have seen already that there are some difference between the object and poiner, the pointer type itself is fixed, so to get the dynamic behavior of typeid, you'd better pass in the real object or reference (which will be treated as the data object)

 

 

type_info class

You may find the type_info class declaration as follow. actually the real implementation can vary from implemenation to implemenation. 

 

 

class type_info { 
private:
	type_info(const type_info&);
	type_info& operator = (const type_info &);
public:
	virtual ~type_info();

	int operator ==(const type_info&) const; 
	int operator!=(const type_info &) const;
	
	const char *name() const; 
};
 

the only way to construct the type_info object is to use the typeid operator. 

 

what is containd in the type_info class is implementation dependant. the name() const char * is the only member guaranteed to be provided by all C++ implementation , though it is possible that implementaion dependant may provide additional support. what can be added, basically any information that a compiler can provide about a type about a type can be added. 

 

  • a list of the class member functions. 
  • what the layout of an object of this clases type looks like in storage, that is , how the member and base subobjects are mapped
class extended_type_info  :public type_info {};
typedef extended_type_info eti;

void func(employee * p)
{
	// downcast from type_info * to extended_type_info*
	if (const eti * eti_p = dynamic_cast<const eti *>(&typeid(*p))) {
		// if dynamic_cast succeeds
		// use extended_type_info information through eti_p
	} else{ 
		// if dynamically fails
		// use standard type_info information
	}
}
 
分享到:
评论

相关推荐

    C++中typeid实现原理详解

    最近看了boost::any类源码,其实现主要依赖typeid操作符。很好奇这样实现的时间和空间开销有多大,决定探一下究竟。 VS2008附带的type_info类只有头文件,没有源文件,声明如下: class type_info { public: ...

    C++关键字大全(67个).txt

    C++关键字大全(67个) asm auto bad_cast bad_typeid bool break case catch char class const const_cast continue default delete do double dynamic_cast else enum except explicit extern false finally float ...

    C++ Primer第四版【中文高清扫描版】.pdf

    【原书名】 C++ Primer (4th Edition) 【原出版社】 Addison Wesley/Pearson 【作者】 (美)Stanley B.Lippman,Josée LaJoie,Barbara E.Moo 【译者】 李师贤 蒋爱军 梅晓勇 林瑛 【丛书名】 图灵计算机科学丛书 ...

    C++关键字详细使用

    operator private protected public register reinterpret_cast return short signed sizeof static static_cast struct switch template this throw true try type_info typedef typeid typename union unsigned ...

    深度探索模C++对象模型PDF

    Placement Operator new的语意 6.3 临时性对象(Temporary Objects) 临时性对象的迷思(神话、传说) 第7章 站在对象模型的类端(On the Cusp of the Object Model) 7.1 Template Template的“具现”行为...

    深度探索C++对象模型 超清版

    Placement Operator new的语意 6.3 临时性对象(Temporary Objects) 临时性对象的迷思(神话、传说) 第7章 站在对象模型的类端(On the Cusp of the Object Model) 7.1 Template Template的“具现”行为...

    《深度探索C++对象模型》(Stanley B·Lippman[美] 著,侯捷 译)

    Placement Operator new的语意 6.3 临时性对象(Temporary Objects) 临时性对象的迷思(神话、传说) 第7章 站在对象模型的类端(On the Cusp of the Object Model) 7.1 Template Template的“具现”行为...

    Thinking_in_C++_中文版【高清+可搜索+可编辑/复制/粘贴+无密码】

    if(typeid(me).before(typeid(you))) //... 那么表示我们正在查询m e在排列顺序中是否在y o u之前。 RT T I的第二个用法叫“安全类型向下映射”。之所以用“向下映射”这个词也是由于类继 承的排列顺序。如果映射一...

    C++运行时获取类型信息的type_info类与bad_typeid异常

    type_info 类 type_info 类描述编译器在程序中生成的类型信息。此类的对象可以有效存储指向类型的名称的指针。 type_info 类还可存储适合比较两个类型是否相等或比较其排列顺序的... _CRTIMP_PURE bool operator==(con

    C++自动析构时的顺序问题

    template &lt;typename&gt;void operator()(T*p)const { os &lt;&lt; "deleting unique_ptr " &lt;&lt;typeid(T).name() &lt;&lt;endl; delete p; } private: ostream &os; }; void demo_general_class_tempalte_...

Global site tag (gtag.js) - Google Analytics