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{booloperator()(TypeInfoRef lhs, TypeInfoRef rhs)const{return lhs.get()== rhs.get();}};intmain(){
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{};intmain(){
Base b1;
Derived d1;const Base * pb =&b1;
std::cout <<typeid(*pb).name()<<"\n";
pb =&d1;
std::cout <<typeid(*pb).name()<<"\n";}