栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++11 的 运行时类型识别type

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++11 的 运行时类型识别type

一、type_info与typeid

类type_info保存关于类型的特定于实现的信息,包括类型的名称,以及比较两个类型是否相等或排序顺序的方法。 这是typeid操作符返回的类。具有如下特点:

    (1)这个类的构造函数是private的,因此用户不能直接构造这样的对象,只能通过typeid()函数来获取这个对象.

    (2)这个类对外提供了name(),operator==()等方法供用户使用.

    (3)typeid()可以对基本的数据类型和对象进行操作,这种情况下,是在编译期静态决定的.

    (4)type_info也可以对类类型和类对象进行操作,分两种情况:如果是声明了虚函数的类对象引用,则typeid()返回的是实际对象的类型信息,在运行时动态决定的;反之(没有定义虚函数,或者即使定义了虚函数但传入的是对象指针),则typeid()返回的是入参声明类型信息,在编译时静态决定的.

// type_index example
#include        // std::cout
#include        // operator typeid
#include       // std::type_index
#include   

int main()
{
    char a = 'a';
    short b = 10;
    int c = 99;
    long d = 20;
    float e = 2.3;
    double f = 4.8;

    cout << typeid(char).name() << endl;
    cout << typeid(a).name() << endl;
    cout << typeid(short).name() << endl;
    cout << typeid(b).name() << endl;
    cout << typeid(int).name() << endl;
    cout << typeid(c).name() << endl;
    cout << typeid(long).name() << endl;
    cout << typeid(d).name() << endl;
    cout << typeid(float).name() << endl;
    cout << typeid(e).name() << endl;
    cout << typeid(double).name() << endl;
    cout << typeid(f).name() << endl;

    if (typeid(f) == typeid(double)) {
        cout << "type is equal" << endl;
    }
    else {
        cout << "type is not equal" << endl;
    }

    system("pause");
    return 0;
}

打印

二、type_index

type_index类在头文件中声明,它是type_info对象的一个封装类,可以用作关联容器(比如map)和无序关联容器(比如unordered_map)的索引。

// type_index example
#include        // std::cout
#include        // operator typeid
#include       // std::type_index
#include   // std::unordered_map
#include   

typedef struct C {};
int main()
{
    std::unordered_map mytypes;
    mytypes[typeid(int)] = "Integer type";
    mytypes[typeid(double)] = "Floating-point type";
    mytypes[typeid(C)] = "Custom class named C";

    std::cout << "int: " << mytypes[typeid(int)] << 'n';
    std::cout << "double: " << mytypes[typeid(double)] << 'n';
    std::cout << "C: " << mytypes[typeid(C)] << 'n';
    system("pause");
    return 0;
}

打印

参考:

std::type_info - cppreference.com

type_index - C++ Reference

C++ type_info简介_weixin_33698043的博客-CSDN博客

C++11 | 运行时类型识别(RTTI)_foruok的博客-CSDN博客_c++11 rtti

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/938214.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号