#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 typetype
. Iftype
is a reference type, the result refers to astd::type_info
object representing the referenced typeIn 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>'
关于c++ - 如何在 C++ 中检查确切的类型信息(使用 cv-ref-pointer 特征)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57282973/