C++ 如何获取对象的类型

c++ how to obtain the type of the object?

本文关键字:类型 取对象 何获 C++      更新时间:2023-10-16

我怎样才能获得以下typeidT& object;其中T是:template<class T>。我正在使用 c++ 代码。我确实测试了:

const std::type_info& ObjT= typeid(object);
std::cout<<"******the objT is: "<<&ObjT<<std::endl;

但它崩溃了。为什么?

如果你想要一个人类可读的名称,请使用 name() 方法:

std::cout<<"******the objT is: "<<ObjT.name()<<std::endl;

你是否包括:

#include <typeinfo>

也许你应该发送

std::cout << typeid(object).name() << std::endl;

也许你正在做&&对象的事实存在问题。

看这里的例子

这是你在做的吗?

#include <typeinfo>
#include <iostream>
template <typename T> 
struct S {
};
int main() {
    S <int> a;
    S <int> & object = a;
    const std::type_info & ObjT = typeid( object );
    std::cout << "******the objT is: "<< ObjT.name() <<  std::endl;
}

这适用于 GCC 4.5.1。