为什么 typeid 返回 int 和 const int 是相同的类型

why typeid returns that int and const int are same types

本文关键字:int 类型 const typeid 返回 为什么      更新时间:2023-10-16
if(typeid(int) == typeid(const int))
       cout << "Same types"<< endl;

程序输出:

相同类型

我错过了什么吗?这些不是同一类型,哈哈。

它们不是同一类型,但typeid运算符剥离constvolatile

从第 5.2.8 节[expr.typeid]

glvalue 表达式的顶级 cv 限定符或作为typeid操作数的类型 id 始终被忽略。

你可能想要这个:

#include <type_traits>
if (std::is_same<int, const int>::value)
    std::cout << "same typesn";
else
    std::cout << "different typesn";