美文网首页
[C++11阅读][3-3-1]RTTI机制与typeid

[C++11阅读][3-3-1]RTTI机制与typeid

作者: 凌霄阁2010 | 来源:发表于2020-07-02 00:10 被阅读0次

    本篇是番外篇,介于auto和decltype之间,讲的是C++对RTTI的支持,既有C++98的函数,也有C++11的新内容。

    RTTI机制

    C++98对动态类型支持就是C++中的运行时类型识别(RTTI)。
    RTTI的机制是为每个类型产生一个type_info类型的数据,程序员可以在程序中使用typeid随时查询一个变量的类型,typeid会返回变量的type_info数据,type_info中的name是类型的名字。C++11中多了hash_code这个成员函数,可以返回每个类唯一的hash值。
    代码动态获得类型,如以下程序,“5”这样的前缀是g++编译器加的。hash_code()函数是动态获取的,不是编译时就决定的。

    #include <iostream>
    #include <typeinfo>
    using namespace std;
    class White{};
    class Black{};
    int main() {
        White a;
        Black b;
        cout << typeid(a).name() << endl;  // 5White
        cout << typeid(b).name() << endl;  // 5Black
        White c;
        bool a_b_sametype = (typeid(a).hash_code() == typeid(b).hash_code());
        bool a_c_sametype = (typeid(a).hash_code() == typeid(c).hash_code());
        cout << "Same type? " << endl;
        cout << "A and B? " << (int)a_b_sametype << endl;  // 0
        cout << "A and C? " << (int)a_c_sametype << endl;  // 1
    }
    

    编译开关

    除了typeid外,RTTI还包括dynamic_cast等特性。由于RTTI会带来一些运行时开销,可以用编译选项关掉。
    gcc选项是-fno-rttion。

    相关文章

      网友评论

          本文标题:[C++11阅读][3-3-1]RTTI机制与typeid

          本文链接:https://www.haomeiwen.com/subject/ublhqktx.html