C/C++编程:std::type_info

#include <typeinfo>
class type_info;
  • 类type_info保有一个类型的实现指定信息,包括类型的名称和比较两个类型相等的方法和相对顺序。这是 typeid 运算符所返回的类。
  • type_info 既非可复制构造 (CopyConstructible) 亦非可复制赋值(CopyAssignable) 。

在这里插入图片描述

std::type_info::before

在这里插入图片描述

 if(typeid(int).before(typeid(char)))
        std::cout << "int goes before char in this implementation.\n";
    else
        std::cout << "char goes before int in this implementation.\n";

在这里插入图片描述

std::type_info::hash_code

在这里插入图片描述

#include <iostream>
#include <typeinfo>
#include <unordered_map>
#include <string>
#include <functional>
#include <memory>

struct A{
    virtual ~A() {};
};

struct B : A{};

struct C : A{};

using TypeInfoRef = std::reference_wrapper<const std::type_info>;

struct Hasher{
    std::size_t  operator()(TypeInfoRef code) const{
        return code.get().hash_code();
    }
};

struct EqualTo{
    bool operator()(TypeInfoRef lhs, TypeInfoRef rhs) const {
        return lhs.get() == rhs.get();
    }
};

int main()
{
   std::unordered_map<TypeInfoRef, std::string, Hasher, EqualTo> type_names;

   type_names[typeid(int )] = "int";
   type_names[typeid(double )] = "double";
   type_names[typeid(A)] = "A";
   type_names[typeid(B)] = "B";
   type_names[typeid(C)] = "C";

   int i;
   double d;
   A a;

    // 注意我们存储指向 A 的指针
    std::unique_ptr<A> b(new B);
    std::unique_ptr<A> c(new C);

    std::cout << "i is " << type_names[typeid(i)] << '\n';
    std::cout << "d is " << type_names[typeid(d)] << '\n';
    std::cout << "a is " << type_names[typeid(a)] << '\n';
    std::cout << "b is " << type_names[typeid(*b)] << '\n';
    std::cout << "c is " << type_names[typeid(*c)] << '\n';
}

在这里插入图片描述

std::type_info::name

在这里插入图片描述

#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";
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值