c++ - 获取变量类型之typeid()

一起 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> 源码结构

源自 cppreference.com

Classes
type_infocontains some type’s information, generated by the implementation. This is the class returned by the typeid operator. (class)
bad_typeidexception that is thrown if an argument in a typeid expression is null (class)
bad_castexception 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

[2] https://zh.wikibooks.org/zh-hans/C%2B%2B/Typeinfo

[3] https://en.cppreference.com/w/cpp/header/typeinfo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值