Hec*_*tor 2 c++ types type-conversion c++11
我正在寻找一种获取类型名称的方法,类似于typeid引用.根据此页面,typeid删除参考.
如果type是引用类型,则结果引用引用的类型.
我正在寻找类似的代码
int x = 5;
int & y = x;
wcout << typeid( y ).name();
Run Code Online (Sandbox Code Playgroud)
但其输出是"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';
Run Code Online (Sandbox Code Playgroud)
打印
int
int&
Run Code Online (Sandbox Code Playgroud)
小智 6
有关C++ 11的方法,请参阅此答案 - 它涉及使用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;
}
Run Code Online (Sandbox Code Playgroud)