C++ typeid关键字

Stella981
• 阅读 432

typeid 是 C++ 的关键字之一,用于获取运行时类型信息,typeid操作符的返回结果是名为type_info的标准库类型的对象的引用(在头文件typeinfo中定义)。

上测试代码:

#include <assert.h>
#include <iostream>
#include <string>
#include <typeinfo>
#include <vector>
#include <cstdio>

using namespace std;

int func(int a) {
    return 0;
}

typedef int(*fun_ptr)(int);

class Base {
public:
    Base() {}
};

int test_typeid1() {
    char              char_ = 'a';
    unsigned char     uchar_ = 'b';
    short             short_ = -16;
    unsigned short    ushort_ = 16;
    int               int_ = -1024;
    unsigned int      uint_ = 1024;
    float             float_ = 1.2f;
    double            double_ = 2.34;
    long              long_ = -12222;
    long long         llong_ = 12222;
    int array[10] = { 0 };
    int* array_ptr = array;
    string            string_("xiongwei");
    vector<int>       int_vector;
    fun_ptr  f = func;
    Base              base_;
    Base* pBase = new Base;
    Base& rBase = base_;

    cout << "char_ type: " << typeid(char_).name() << std::endl;
    assert(typeid(char).name() == typeid(char_).name());

    std::cout << "uchar type: " << typeid(uchar_).name() << std::endl; // uchar type: unsigned char
    assert(typeid(unsigned char).name() == typeid(uchar_).name());

    std::cout << "short_ type: " << typeid(short_).name() << std::endl; // short_ type: short
    assert(typeid(short).name() == typeid(short_).name());

    std::cout << "ushort_ type: " << typeid(ushort_).name() << std::endl; // ushort_ type: unsigned short
    assert(typeid(unsigned short).name() == typeid(ushort_).name());

    std::cout << "int_ type: " << typeid(int_).name() << std::endl; // int_ type: int
    assert(typeid(int).name() == typeid(int_).name());

    std::cout << "uint_ type: " << typeid(uint_).name() << std::endl; // uint_ type: unsigned int
    assert(typeid(unsigned int).name() == typeid(uint_).name());

    std::cout << "float_ type: " << typeid(float_).name() << std::endl; // float_ type: float
    assert(typeid(float).name() == typeid(float_).name());

    std::cout << "double_ type: " << typeid(double_).name() << std::endl; // double_ type: double
    assert(typeid(double).name() == typeid(double_).name());

    std::cout << "long_ type: " << typeid(long_).name() << std::endl; // long_ type: long
    assert(typeid(long).name() == typeid(long_).name());

    std::cout << "llong_ type: " << typeid(llong_).name() << std::endl; // llong_ type: __int64
    assert(typeid(long long).name() == typeid(llong_).name());

    std::cout << "array[] type: " << typeid(array).name() << std::endl; // array[] type: int [10]
    assert(typeid(int[10]).name() == typeid(array).name());

    std::cout << "array_header type: " << typeid(array_ptr).name() << std::endl; // array_header type: int * __ptr64
    assert(typeid(int*).name() == typeid(array_ptr).name());

    std::cout << "string_ type: " << typeid(string_).name() << std::endl; // string_ type: class std::basic_string<char,struct std::char_traits<char>, class std::allocator<char>>
    assert(typeid(std::string).name() == typeid(string_).name());

    std::cout << "int_vector type: " << typeid(int_vector).name() << std::endl; // int_vector type: class std::vector<int,class std::allocator<int>>
    assert(typeid(std::vector<int>).name() == typeid(int_vector).name());

    std::cout << "f type: " << typeid(f).name() << std::endl; // f type : int(__cdecl*)(int)
    assert(typeid(int(*)(int)).name() == typeid(f).name());

    std::cout << "Base_ type: " << typeid(base_).name() << std::endl; // Base_ type: class Base
    assert(typeid(class Base).name() == typeid(base_).name());

    std::cout << "pBase_ type: " << typeid(pBase).name() << std::endl; // pBase_ type: class Base * __ptr64
    assert(typeid(class Base*).name() == typeid(pBase).name());

    std::cout << "rBase_ type: " << typeid(rBase).name() << std::endl; // Base__ type: class Base
    assert(typeid(class Base&).name() == typeid(rBase).name());
    return 0;

}

void test_typeid2() {

    struct Base {

    }; // non-polymorphic
    struct Derived : Base {

    };

    struct Base2 {
        virtual void foo() {}
    }; // polymorphic

    struct Derived2 : Base2 {

    };

    int myint = 50;
    std::string mystr = "string";
    double *mydoubleptr = NULL;

    std::cout << "myint has type: " << typeid(myint).name() << '\n' // myint has type: int
        << "mystr has type: " << typeid(mystr).name() << '\n' // mystr has type: class std::basic_string<char, struct std::char_traits<char>, class std::allocator<char>>
        << "mydoubleptr has type: " << typeid(mydoubleptr).name() << '\n'; // mydoubleptr has type: double * __ptr64

                                                                           // std::cout << myint is a glvalue expression of polymorphic type; it is evaluated
    const std::type_info& r1 = typeid(std::cout); // 50

    std::cout << "#std::cout<<myint has type : " << r1.name() << '\n';
    // std::cout<<myint has type: class std::basic_ostream<char, struct std::char_traits<char>>

    const std::type_info& r2 = typeid(std::printf("%d\n", myint));
    std::cout << "printf(\"%d\\n\",myint) has type : " << r2.name() << '\n'; // printf(\"%d\\n\",myint) has type : int

    Derived d1;
    Base& b1 = d1;
    std::cout << "reference to non-polymorphic base: " << typeid(b1).name() << '\n'; // reference to non-polymorphic base: struct 'int __cdecl test_typeid2(void)'::'2'::Base

    Derived2 d2;
    Base2& b2 = d2;
    std::cout << "reference to polymorphic base: " << typeid(b2).name() << '\n'; // reference to polymorphic base: struct 'int __cdecl test_typeid2(void)'::'3'::Derived2

    try {
        // dereferencing a null pointer: okay for a non-polymoprhic expression  
        std::cout << "mydoubleptr points to " << typeid(*mydoubleptr).name() << '\n'; // mydoubleptr points to double  
                                                                                      // dereferencing a null pointer: not okay for a polymorphic lvalue  
        Derived2* bad_ptr = NULL;
        std::cout << "bad_ptr points to...";  // bad_ptr points to...   
        std::cout << typeid(*bad_ptr).name() << '\n';
    }
    catch (const std::bad_typeid& e) {
        std::cout << " caught " << e.what() << '\n'; // caught Attempted a typeid of NULL pointer!  
    }

}

template < typename T >
T max(T arg1, T arg2) {
    std::cout << typeid(T).name() << "s compared." << std::endl;
    return (arg1 > arg2 ? arg1 : arg2);
}

int test_typeid3()
{
    class Base {
    public:
        virtual void vvfunc() {}
    };

    class Derived : public Base {};

    Derived* pd = new Derived;
    Base* pb = pd;
    std::cout << typeid(pb).name() << std::endl;   //prints "class Base *" // class 'int __cdecl test_typeid3(void)'::'2'::Base * __ptr64  
    std::cout << typeid(*pb).name() << std::endl;   //prints "class Derived" // class 'int __cdecl test_typeid3(void)'::'2'::Derived  
    std::cout << typeid(pd).name() << std::endl;   //prints "class Derived *" // class 'int __cdecl test_typeid3(void)'::'2'::Derived * __ptr64  
    std::cout << typeid(*pd).name() << std::endl;   //prints "class Derived" // class 'int __cdecl test_typeid3(void)'::'2'::Derived  
    delete pd;

    float a = 1.2, b = 3.4;
    max(a, b); // floats compared  

    max<int>(1,2);

    return 0;
}

int main() {

    test_typeid1();
    cout << "---------------------------------------" << endl;
    test_typeid2();
    test_typeid3();

    system("pause");
    return 0;
}
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Karen110 Karen110
2年前
一篇文章带你了解JavaScript日期
日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
4个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这