一起 coding,一起学习,一起进步 —— sunshine
typeid() 定义
- 在c++中,typeid用于返回变量、指针或引用所指对象的实际类型
- 需要注意的是 typeid是操作符,不是函数!类似与sizeof 计算变量或者是类型所占空间大小
typeid() 使用
-
运行时获知变量类型名称,可以使用 typeid(变量).name(),需要注意不是所有编译器都输出"int"、"float"等之类的名称,对于这类的编译器可以这样使用:float f = 1.1f; if( typeid(f) == typeid(0.0f) ) ……
-
对非引用类型,typeid是在编译时期识别的,只有引用类型才会在运行时识别。
typeInfo 头文件
<typeinfo>
是C++标准库中的一个头文件,定义了C++标准中用于运算符b:typeid
返回结果类型及抛出的异常类型。
类
- type_info:包含着一个类型的信息。可以通过成员函数
name()
来获知其名字字符串。是运算符b:typeid
返回结果类型。 - bad_typeid:异常类型。当typeid表达式的实参为null时抛出该异常。
- bad_cast:异常类型。当一个无效的dynamic_cast表达式执行时抛出该异常。
使用示例
#include <iostream>
#include <typeinfo>
struct Base { virtual ~Base() = default; };
struct Derived : Base {};
int main() {
Base b1;
Derived d1;
const Base *pb = &b1;
std::cout << typeid(*pb).name() << '\n';
pb = &d1;
std::cout << typeid(*pb).name() << '\n';
}
<typeinfo> 源码结构
Classes
type_info | contains some type’s information, generated by the implementation. This is the class returned by the typeid operator. (class) |
---|---|
bad_typeid | exception that is thrown if an argument in a typeid expression is null (class) |
bad_cast | exception that is thrown by an invalid dynamic_cast expression, i.e. a cast of reference type fails (class) |
Synopsis
namespace std {
class type_info;
class bad_cast;
class bad_typeid;
}
Class std::type_info
class type_info {
public:
virtual ~type_info();
bool operator==(const type_info& rhs) const noexcept;
bool operator!=(const type_info& rhs) const noexcept;
bool before(const type_info& rhs) const noexcept;
size_t hash_code() const noexcept;
const char* name() const noexcept;
type_info(const type_info& rhs) = delete; // cannot be copied
type_info& operator=(const type_info& rhs) = delete; // cannot be copied
};
Class std::bad_cast
class bad_cast : public exception {
public:
bad_cast() noexcept;
bad_cast(const bad_cast&) noexcept;
bad_cast& operator=(const bad_cast&) noexcept;
const char* what() const noexcept override;
};
Class std::bad_typeid
class bad_typeid : public exception {
public:
bad_typeid() noexcept;
bad_typeid(const bad_typeid&) noexcept;
bad_typeid& operator=(const bad_typeid&) noexcept;
const char* what() const noexcept override;
};
参考:
[1] https://baike.baidu.com/item/typeid/10657940