C++中的typeid

2023年8月10日,周四下午


目录


概述

typeid是 C++ 中的运算符,用于获取表达式或类型的运行时类型信息。

它返回一个std::type_info对象,该对象包含有关类型的信息,例如类型的名称。

typeid的用法

用法1

typeid(expression)

expression可以是一个变量、对象、函数调用、类型转换等:

int x = 10;
double y = 3.14;
const char* str = "Hello";

typeid(x);
typeid(y);  
typeid(str); 

用法2

typeid(type)

type可以是一个具体的类型、类型别名或模板参数等:

typeid(int);
typeid(double);  
typeid(const char*); 

用法3

使用 std::type_info::name() 获取类型的名称:

typeid(expression).name()
typeid(type).name()

这将返回一个 const char* 类型的字符串,表示类型的名称。注意,类型的名称是平台相关的,可能具有不同的格式和表示方式。

下面列出了一些常见的typeid根据类型名称返回const char*字符串:

  • int 对应 i
  • char 对应 c
  • float 对应 f
  • double 对应 d
  • bool 对应 b
  • void 对应 v
  • unsigned 对应 j
  • long 对应 l
  • short 对应 s
  • unsigned long 对应 m
  • unsigned short 对应 t
  • const 对应 K
  • volatile 对应 V
  • * 对应 P
  • & 对应 R
  • && 对应 O
  • [] 对应 A
  • () 对应 F

举例说明

#include <iostream>
#include <typeinfo>

void printType(const std::type_info& typeInfo) {
    std::cout << "Type: " << typeInfo.name() << std::endl;
}

int main() {
    int x = 10;
    double y = 3.14;
    const char* str = "Hello";

    printType(typeid(x));    
    printType(typeid(y));  
    printType(typeid(str)); 

    return 0;
}

i对应int

d对应double

P对应*,K对应const,c对应char

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

巨龙之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值