`

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
	}
}
 
分享到:
评论

相关推荐

    cpp代码-typeid

    在C++编程语言中,`typeid`是一个非常重要的运行时类型信息(RTTI,Runtime Type Information)的关键字。它允许程序员在程序运行时查询对象或指针的实际类型,这对于多态性和动态类型检查非常有用。在本教程中,...

    C++关键字-全.pdf

    22. `operator`:`operator`用于重载运算符,使用户自定义类型支持标准运算符。 23. `private`、`protected`、`public`:这三个关键字定义类的成员访问权限,分别代表私有、受保护和公有。 24. `register`:请求...

    C++常用运算符重载简介

    : , sizeof , typeid 这几个运算符不能被重载,其他运算符都能被重载。 ### 重载不能改变该运算符用于内置类型时的函义 程序员不能改变运算符+用于两个int型时的含义。 ### 运算符函数的参数至少有一个必须是类...

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

    总的来说,`type_info`类和`bad_typeid`异常是C++运行时类型信息基础设施的重要组成部分,它们使得在程序运行过程中能够检查和处理不同类型的数据,从而增强代码的灵活性和安全性。理解这些概念对于深入学习C++的...

    C++中不能重载的运算符

    ### C++中不可重载的运算符及其规则 在C++编程语言中,为了提高代码的灵活性和可读性,提供了运算符重载这一特性。然而,并非所有的运算符都可以被重载。本文将详细介绍那些不可重载的运算符以及自增(`++`)和自减(`...

    C++学习随手笔记--基础方面

    `false`, `float`, `for`, `friend`, `goto`, `if`, `inline`, `int`, `long`, `mutable`, `namespace`, `new`, `operator`, `private`, `protected`, `public`, `register`, `reinterpret_cast`, `return`, `short...

    C++中的运算符的重载

    :`、`sizeof`、`typeid`。 3. 不能改变运算符的参数个数、优先级或结合性。 4. 重载运算符不能使用默认参数。 运算符重载的语法通常形式为`返回类型 operator@( 参数表 )`,其中`@`代表要重载的运算符。对于类内的...

    C++中typeid实现原理详解

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

    C++高级语言编程思想

    `typeid`操作符是C++中用于实现RTTI的主要方式之一。它接收一个表达式作为参数,并返回一个表示该表达式类型的`std::type_info`对象。这个对象包含了类型的信息,包括类型的名字。 - **语法**: `std::type_info & ...

    c++常用术语英汉互译

    - **operator**(运算符重载):允许我们自定义操作符的行为。 - **private**(私有):限定符,用于限制对类成员的访问。 - **protected**(受保护):限定符,介于`private`和`public`之间,子类可以访问父类的受...

    c++关键字解释大全

    ### C++关键字详解 在C++编程语言中,关键字具有特定的语法意义,它们由编译器识别并赋予特殊含义。下面将详细介绍一系列C++的关键字及其用途。 #### asm(汇编指令) - **功能**:`asm`关键字用于嵌入汇编代码到...

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

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

    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++操作符重载手册

    特定操作符如`operator=`、`operator[]`、`operator()`和`operator-&gt;`只能是成员函数。 4. **操作符`-&gt;`** 返回值应是类指针或支持`-&gt;`操作的对象。 5. **自增/自减操作符** `operator++`和`operator--`,前缀形式...

    C++电子教案第二章 C++语言编程基础.ppt

    - ANSI C++独有的关键词:`bool`、`catch`、`class`、`const_cast`、`delete`、`dynamic_cast`、`explicit`、`false`、`friend`、`inline`、`mutable`、`namespace`、`new`、`nullptr`、`operator`、`private`、`...

    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语言32以及C++63个关键字及其含义.doc

    - 更多C++关键字包括`explicit`、`friend`、`mutable`、`new`、`operator`、`private`、`protected`、`public`、`reinterpret_cast`、`return`、`static_cast`、`template`、`this`、`throw`、`try`、`typeid`、`...

    小白入门C++入门语法资料PDF

    * operator * this * wchar_t * continue * float * private * throw * while * default * friend * protected * true 提示:在给变量或者常量起名称时候,不要用C++的关键字,否则会产生歧义。 1.6 标识符命名...

Global site tag (gtag.js) - Google Analytics