C++中的typeInfo用法总结

最近在做测试,在大型程序中,模板类型加上继承关系搞得我混乱,还好有tpyeinfo帮助捋顺关系。

typeInfo与typeid简单总结说明:

  1. 和sizeof这类的操作符一样,typeid是C++的关键字之一。
  2. typeid操作符的返回结果是名为type_info的标准库类型的对象的引用(在头文件typeinfo中定义)
  3. C++并没有规定typeid实现标准,各个编译器可能会不一样。
  4. 编译器会为每一种typeid操作的类型生成一份保存在数据段的type_info数据。
  5. 每种类型的type_info数据长度依赖于类型名称,至少9个字节。

1. == 和!=操作

判断两个数据类型是否相同,判定的数据可以是自己定义的数据类型。

代码示例:

#include <iostream>   // std::cout
#include <typeinfo>   // operator typeid

struct Base {};
struct Derived : Base {};
struct Poly_Base {virtual void Member(){}};
struct Poly_Derived: Poly_Base {};

typedef int my_int_type;

int main() {
  std::cout << std::boolalpha;

  // fundamental types:
  std::cout << "int vs my_int_type: ";
  std::cout << ( typeid(int) == typeid(my_int_type) ) << '\n';

  // class types:
  std::cout << "Base vs Derived: ";
  std::cout << ( typeid(Base)==typeid(Derived) ) << '\n';

  // non-polymorphic object:
  Base* pbase = new Derived;

  std::cout << "Base vs *pbase: ";
  std::cout << ( typeid(Base)==typeid(*pbase) ) << '\n';

  // polymorphic object:
  Poly_Base* ppolybase = new Poly_Derived;

  std::cout << "Poly_Base vs *ppolybase: ";
  std::cout << ( typeid(Poly_Base)==typeid(*ppolybase) ) << '\n';

  return 0;
}

输出:

int vs my_int_type: true
Base vs Derived: false
Base vs *pbase: true
Poly_Base vs *ppolybase: false

2. name操作

获取数据类型的名字,这个名字是C风格的字符串指针。

##include <iostream>       // std::cout
#include <typeinfo>       // operator typeid

struct Base {};
struct Derived : Base {};
template<class T>
void swap(T a, T b)
{
    std::cout << "T is: " << typeid(T).name() << '\n';
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    int i;
    int * ptr;
    std::cout << "int is: " << typeid(int).name() << '\n';
    std::cout << "  i is: " << typeid(i).name() << '\n';
    std::cout << " pi is: " << typeid(ptr).name() << '\n';
    std::cout << "*pi is: " << typeid(*ptr).name() << '\n';

    Base base;

    std::cout << "Base is: " << typeid(Base).name() << '\n';
    std::cout << "base is: " << typeid(base).name() << '\n';
    std::cout << "Derived is: " << typeid(Derived).name() << '\n';

    swap(1,2);

    return 0;
}

输出:

int is: i
  i is: i
 pi is: Pi
*pi is: i
Base is: 4Base
base is: 4Base
Derived is: 7Derived
T is: i
  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非晚非晚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值