c++ - 如何在 C++ 中检查确切的类型信息(使用 cv-ref-pointer 特征)?

标签 c++ standards typetraits abi typeid

#include <iostream>

using namespace std;

int main()
{
    cout << typeid(int).name() << endl;
    cout << typeid(int&).name() << endl;
    cout << typeid(int&&).name() << endl;
    cout << typeid(const int).name() << endl;
    cout << typeid(const int&).name() << endl;
    cout << typeid(const int&&).name() << endl;
}

我认为输出应该是:

int
int&
int&&
const int
const int&
const int&&

然而,真正的输出是:

int
int
int
int
int
int

clang 和 vc++ 都是一样的。

在 C++ 中是否有一种可靠的方法来检查确切的类型名称(带有 cv-ref-pointer 特征)?

最佳答案

请注意,当您将引用类型传递给 typeid operator 时,结果 std::type_info 对象表示引用的类型。并且 cv-qualifiers 将被忽略。

1) Refers to a std::type_info object representing the type type. If type is a reference type, the result refers to a std::type_info object representing the referenced type

In all cases, cv-qualifiers are ignored by typeid (that is, typeid(const T) == typeid(T))

请注意 std::type_info::name返回是实现定义的。

您可以应用 Effective Modern C++ 中的技巧 (Scott Meyers) 第 4 项:了解如何查看推导类型,以便在编译时获取类型名称。例如

template <typename>
struct TD;

然后将其用作

TD<int> td;

您会收到一些提及类型名称的消息,例如

error: implicit instantiation of undefined template 'TD<int>'

LIVE (clang)

关于c++ - 如何在 C++ 中检查确切的类型信息(使用 cv-ref-pointer 特征)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57282973/

相关文章:

c++ - 在 Redhat : alternatives to system() 上从 C++ 解压缩文件

c++ - malloc() 可能导致内存泄漏

没有 typedef 的模板类的 C++ 模板,这可能吗?

C++ std::variant - 类型特征以验证所包含的变体类型是否满足某些假设

c++ - 为什么这个 sfinae 不起作用?

c++ - 按位或顺序的评估顺序

c# - C# 中的结构对齐

java - 为什么有这么多具有​​相同功能的 Java 框架?

c - 为什么 sys/stat.h 不使用 -std=c1x 定义 ino_t?

C++检测类型是否为字符串对象