是否有 typeid 供参考?
Is there a typeid for references?
我正在寻找一种获取类型名称的方法,类似于 typeid
但仅供参考。根据 this page,typeid
删除引用。
If type is a reference type, the result refers to the referenced type.
我正在寻找类似于
的代码
int x = 5;
int & y = x;
wcout << typeid( y ).name();
但其输出是 "int &" 而不是 "int"。
据我所知,唯一可移植的方法是使用 Boost.TypeIndex
std::cout << boost::typeindex::type_id_with_cvr<decltype(x)>().pretty_name() << '\n';
std::cout << boost::typeindex::type_id_with_cvr<decltype(y)>().pretty_name() << '\n';
打印
int
int&
有关 C++11 的实现方式,请参阅 this answer - 它涉及使用 type_traits。这是代码的相关部分:
#include <type_traits>
#include <typeinfo>
#ifndef _MSC_VER
# include <cxxabi.h>
#endif
#include <memory>
#include <string>
#include <cstdlib>
template <class T>
std::string
type_name()
{
typedef typename std::remove_reference<T>::type TR;
std::unique_ptr<char, void(*)(void*)> own
(
#ifndef _MSC_VER
abi::__cxa_demangle(typeid(TR).name(), nullptr,
nullptr, nullptr),
#else
nullptr,
#endif
std::free
);
std::string r = own != nullptr ? own.get() : typeid(TR).name();
if (std::is_const<TR>::value)
r += " const";
if (std::is_volatile<TR>::value)
r += " volatile";
if (std::is_lvalue_reference<T>::value)
r += "&";
else if (std::is_rvalue_reference<T>::value)
r += "&&";
return r;
}
我正在寻找一种获取类型名称的方法,类似于 typeid
但仅供参考。根据 this page,typeid
删除引用。
If type is a reference type, the result refers to the referenced type.
我正在寻找类似于
的代码int x = 5;
int & y = x;
wcout << typeid( y ).name();
但其输出是 "int &" 而不是 "int"。
据我所知,唯一可移植的方法是使用 Boost.TypeIndex
std::cout << boost::typeindex::type_id_with_cvr<decltype(x)>().pretty_name() << '\n';
std::cout << boost::typeindex::type_id_with_cvr<decltype(y)>().pretty_name() << '\n';
打印
int
int&
有关 C++11 的实现方式,请参阅 this answer - 它涉及使用 type_traits。这是代码的相关部分:
#include <type_traits>
#include <typeinfo>
#ifndef _MSC_VER
# include <cxxabi.h>
#endif
#include <memory>
#include <string>
#include <cstdlib>
template <class T>
std::string
type_name()
{
typedef typename std::remove_reference<T>::type TR;
std::unique_ptr<char, void(*)(void*)> own
(
#ifndef _MSC_VER
abi::__cxa_demangle(typeid(TR).name(), nullptr,
nullptr, nullptr),
#else
nullptr,
#endif
std::free
);
std::string r = own != nullptr ? own.get() : typeid(TR).name();
if (std::is_const<TR>::value)
r += " const";
if (std::is_volatile<TR>::value)
r += " volatile";
if (std::is_lvalue_reference<T>::value)
r += "&";
else if (std::is_rvalue_reference<T>::value)
r += "&&";
return r;
}