boost::typeIndex 的相关探究
boost::typeIndex 的相关探究 Effective Modern C++ 的 Item 4: Know how to view deduced types. 中提到了 Boost::typeindex 的使用,但并没有讲到其实现原理。 1. typeid 操作符 typeid 是 C++ 中的一个操作符,可以用于获取类型的信息,常常用在必须知道多态对象的动态类型,或是识别静态类型的地方。 我们可以写一个简单的 demo 用于获取对象类型相关的信息,需要包含 tepyinfo 头文件: #include <iostream> #include <typeinfo> using namespace std; class Foo {}; int main() { cout << "1: " << typeid(1).name() << endl; cout << "int: " << typeid(int).name() << endl; // 和 sizeof 操作符类似,typeid 也可以直接对数据类型(比如 int)进行操作 cout << "typeid: " << typeid(typeid(int)).name() << endl; cout << "typeid: " << typeid(const type_info &).name() << endl; const Foo *foo = new Foo(); cout << "foo: " << typeid(foo).name() << endl; cout << "*foo: " << typeid(*foo).name() << endl; cout << "Foo: " << typeid(Foo).name() << endl; } [joelzychen@DevCloud ~/typeid]$ g++ -std=c++11 -otypeid_test typeid_test.cpp [joelzychen@DevCloud ~/typeid]$ ./typeid_test 1: i int: i typeid: N10__cxxabiv123__fundamental_type_infoE typeid: St9type_info foo: PK3Foo *foo: 3Foo Foo: 3Foo std::type_info::name() 函数返回的字符串中,在 GCC 和 Clang 的实现里一般 i 代表 int,P 代表 pointer,K 代表 const,数字用于标识其后跟随了几个字符;我们可以将这段代码使用微软的 MSVC 编译运行,得到更加直观的输出: ...