是否有可能在标准c++中打印变量的类型?

例如:

int a = 12;
cout << typeof(a) << endl;

预期的输出:

int
604049 次浏览

试一试:

#include <typeinfo>


// …
std::cout << typeid(a).name() << '\n';

您可能必须在编译器选项中激活RTTI才能使其工作。此外,它的输出取决于编译器。它可能是一个原始类型名称或名称混乱符号或介于两者之间的任何东西。

别忘了加上<typeinfo>

我相信您所指的是运行时类型标识。你可以通过做来达到以上目的。

#include <iostream>
#include <typeinfo>


using namespace std;


int main() {
int i;
cout << typeid(i).name();
return 0;
}

你可以上特质课。喜欢的东西:

#include <iostream>
using namespace std;


template <typename T> class type_name {
public:
static const char *name;
};


#define DECLARE_TYPE_NAME(x) template<> const char *type_name<x>::name = #x;
#define GET_TYPE_NAME(x) (type_name<typeof(x)>::name)


DECLARE_TYPE_NAME(int);


int main()
{
int a = 12;
cout << GET_TYPE_NAME(a) << endl;
}

DECLARE_TYPE_NAME定义的存在是为了让您更容易地为您预计需要的所有类型声明这个trait类。

这可能比涉及typeid的解决方案更有用,因为您可以控制输出。例如,在我的编译器上使用typeid代替long long给出“x”。

您可以使用模板。

template <typename T> const char* typeof(T&) { return "unknown"; }    // default
template<> const char* typeof(int&) { return "int"; }
template<> const char* typeof(float&) { return "float"; }

在上面的例子中,当类型不匹配时,它将打印“unknown”。

注意,c++的RTTI特性生成的名称是可移植的。 例如,类

MyNamespace::CMyContainer<int, test_MyNamespace::CMyObject>

将有以下名称:

// MSVC 2003:
class MyNamespace::CMyContainer[int,class test_MyNamespace::CMyObject]
// G++ 4.2:
N8MyNamespace8CMyContainerIiN13test_MyNamespace9CMyObjectEEE

所以不能将此信息用于序列化。但是typeid(a).name()属性仍然可以用于日志/调试目的

涉及RTTI (typeid)的其他答案可能是您想要的,只要:

  • 您可以承担内存开销(对于某些编译器,这可能相当大)
  • 编译器返回的类名很有用

另一种选择(类似于Greg Hewgill的答案)是建立一个特征的编译时表。

template <typename T> struct type_as_string;


// declare your Wibble type (probably with definition of Wibble)
template <>
struct type_as_string<Wibble>
{
static const char* const value = "Wibble";
};

注意,如果你将声明包装在宏中,你将在声明带有多个参数的模板类型时遇到麻烦(例如std::map),这是由于逗号的原因。

要访问变量类型的名称,您所需要的是

template <typename T>
const char* get_type_as_string(const T&)
{
return type_as_string<T>::value;
}

非常丑陋,但如果你只想要编译时信息(例如调试):

auto testVar = std::make_tuple(1, 1.0, "abc");
decltype(testVar)::foo= 1;

返回:

Compilation finished with errors:
source.cpp: In function 'int main()':
source.cpp:5:19: error: 'foo' is not a member of 'std::tuple<int, double, const char*>'

如前所述,typeid().name()可能返回一个损坏的名称。在GCC(和其他一些编译器)中,你可以使用以下代码来解决它:

#include <cxxabi.h>
#include <iostream>
#include <typeinfo>
#include <cstdlib>


namespace some_namespace { namespace another_namespace {


class my_class { };


} }


int main() {
typedef some_namespace::another_namespace::my_class my_type;
// mangled
std::cout << typeid(my_type).name() << std::endl;


// unmangled
int status = 0;
char* demangled = abi::__cxa_demangle(typeid(my_type).name(), 0, 0, &status);


switch (status) {
case -1: {
// could not allocate memory
std::cout << "Could not allocate memory" << std::endl;
return -1;
} break;
case -2: {
// invalid name under the C++ ABI mangling rules
std::cout << "Invalid name" << std::endl;
return -1;
} break;
case -3: {
// invalid argument
std::cout << "Invalid argument to demangle()" << std::endl;
return -1;
} break;
}
std::cout << demangled << std::endl;


free(demangled);


return 0;

c++ 11更新到一个非常老的问题:在c++中打印变量类型。

公认的(很好的)答案是使用typeid(a).name(),其中a是一个变量名。

现在在c++ 11中,我们有decltype(x),它可以将表达式转换为类型。decltype()有自己的一套非常有趣的规则。例如,decltype(a)decltype((a))通常是不同的类型(一旦这些原因暴露出来,就会有很好的和可以理解的原因)。

我们值得信赖的typeid(a).name()会帮助我们探索这个美丽的新世界吗?

不。

但是这个工具并不复杂。我就是用这个工具来回答这个问题的。我将比较这个新工具和typeid(a).name()。这个新工具实际上是建立在typeid(a).name()之上的。

根本问题是:

typeid(a).name()

丢弃cv限定符、引用和左值/右值。例如:

const int ci = 0;
std::cout << typeid(ci).name() << '\n';

对于我输出:

i

我猜MSVC的输出:

int

也就是说,const不见了。这不是QOI(实施质量)问题。标准要求这种行为。

以下是我的建议:

template <typename T> std::string type_name();

可以这样使用:

const int ci = 0;
std::cout << type_name<decltype(ci)>() << '\n';

对我来说输出:

int const

我还没有在MSVC上测试过这个。但我欢迎那些喜欢的人给我反馈。

c++ 11解决方案

我对非msvc平台使用__cxa_demangle,正如ipapadop在他对需求类型的回答中所推荐的那样。但在MSVC上,我相信typeid会要求命名(未经测试)。这个核心包含一些简单的测试,用于检测、恢复和报告cv限定符和对输入类型的引用。

#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;
}

结果

有了这个解决方案,我可以这样做:

int& foo_lref();
int&& foo_rref();
int foo_value();


int
main()
{
int i = 0;
const int ci = 0;
std::cout << "decltype(i) is " << type_name<decltype(i)>() << '\n';
std::cout << "decltype((i)) is " << type_name<decltype((i))>() << '\n';
std::cout << "decltype(ci) is " << type_name<decltype(ci)>() << '\n';
std::cout << "decltype((ci)) is " << type_name<decltype((ci))>() << '\n';
std::cout << "decltype(static_cast<int&>(i)) is " << type_name<decltype(static_cast<int&>(i))>() << '\n';
std::cout << "decltype(static_cast<int&&>(i)) is " << type_name<decltype(static_cast<int&&>(i))>() << '\n';
std::cout << "decltype(static_cast<int>(i)) is " << type_name<decltype(static_cast<int>(i))>() << '\n';
std::cout << "decltype(foo_lref()) is " << type_name<decltype(foo_lref())>() << '\n';
std::cout << "decltype(foo_rref()) is " << type_name<decltype(foo_rref())>() << '\n';
std::cout << "decltype(foo_value()) is " << type_name<decltype(foo_value())>() << '\n';
}

输出为:

decltype(i) is int
decltype((i)) is int&
decltype(ci) is int const
decltype((ci)) is int const&
decltype(static_cast<int&>(i)) is int&
decltype(static_cast<int&&>(i)) is int&&
decltype(static_cast<int>(i)) is int
decltype(foo_lref()) is int&
decltype(foo_rref()) is int&&
decltype(foo_value()) is int

注意(例如)decltype(i)decltype((i))之间的区别。前者是i宣言类型。后者是“类型”;表达式 i。(表达式从来没有引用类型,但是按照约定decltype表示带有左值引用的左值表达式)。

因此,除了探索和调试您自己的代码之外,这个工具是了解decltype的绝佳工具。

相反,如果我只是在typeid(a).name()上构建这个,而不添加回丢失的cv-qualifiers或引用,输出将是:

decltype(i) is int
decltype((i)) is int
decltype(ci) is int
decltype((ci)) is int
decltype(static_cast<int&>(i)) is int
decltype(static_cast<int&&>(i)) is int
decltype(static_cast<int>(i)) is int
decltype(foo_lref()) is int
decltype(foo_rref()) is int
decltype(foo_value()) is int

也就是说,所有的引用和简历修饰符都被剥离了。

c++ 14更新

就在你认为自己已经找到了解决问题的办法时,总会有人不知从哪里冒出来,给你展示一个更好的方法。: -)

这个答案欢乐的聚会展示了如何在编译时在c++ 14中获取类型名。这是一个出色的解决方案,原因如下:

  1. 它在编译时!
  2. 你让编译器本身来做这项工作,而不是一个库(甚至是std::lib)。这意味着对于最新的语言特性(如lambdas)会得到更准确的结果。

聚会的 回答并没有完全为VS布局一切,我稍微调整了一下他的代码。但由于这个答案获得了很多点击量,花点时间去那里为他的答案投票,如果没有投票,这个更新就不会发生。

#include <cstddef>
#include <stdexcept>
#include <cstring>
#include <ostream>


#ifndef _MSC_VER
#  if __cplusplus < 201103
#    define CONSTEXPR11_TN
#    define CONSTEXPR14_TN
#    define NOEXCEPT_TN
#  elif __cplusplus < 201402
#    define CONSTEXPR11_TN constexpr
#    define CONSTEXPR14_TN
#    define NOEXCEPT_TN noexcept
#  else
#    define CONSTEXPR11_TN constexpr
#    define CONSTEXPR14_TN constexpr
#    define NOEXCEPT_TN noexcept
#  endif
#else  // _MSC_VER
#  if _MSC_VER < 1900
#    define CONSTEXPR11_TN
#    define CONSTEXPR14_TN
#    define NOEXCEPT_TN
#  elif _MSC_VER < 2000
#    define CONSTEXPR11_TN constexpr
#    define CONSTEXPR14_TN
#    define NOEXCEPT_TN noexcept
#  else
#    define CONSTEXPR11_TN constexpr
#    define CONSTEXPR14_TN constexpr
#    define NOEXCEPT_TN noexcept
#  endif
#endif  // _MSC_VER


class static_string
{
const char* const p_;
const std::size_t sz_;


public:
typedef const char* const_iterator;


template <std::size_t N>
CONSTEXPR11_TN static_string(const char(&a)[N]) NOEXCEPT_TN
: p_(a)
, sz_(N-1)
{}


CONSTEXPR11_TN static_string(const char* p, std::size_t N) NOEXCEPT_TN
: p_(p)
, sz_(N)
{}


CONSTEXPR11_TN const char* data() const NOEXCEPT_TN {return p_;}
CONSTEXPR11_TN std::size_t size() const NOEXCEPT_TN {return sz_;}


CONSTEXPR11_TN const_iterator begin() const NOEXCEPT_TN {return p_;}
CONSTEXPR11_TN const_iterator end()   const NOEXCEPT_TN {return p_ + sz_;}


CONSTEXPR11_TN char operator[](std::size_t n) const
{
return n < sz_ ? p_[n] : throw std::out_of_range("static_string");
}
};


inline
std::ostream&
operator<<(std::ostream& os, static_string const& s)
{
return os.write(s.data(), s.size());
}


template <class T>
CONSTEXPR14_TN
static_string
type_name()
{
#ifdef __clang__
static_string p = __PRETTY_FUNCTION__;
return static_string(p.data() + 31, p.size() - 31 - 1);
#elif defined(__GNUC__)
static_string p = __PRETTY_FUNCTION__;
#  if __cplusplus < 201402
return static_string(p.data() + 36, p.size() - 36 - 1);
#  else
return static_string(p.data() + 46, p.size() - 46 - 1);
#  endif
#elif defined(_MSC_VER)
static_string p = __FUNCSIG__;
return static_string(p.data() + 38, p.size() - 38 - 7);
#endif
}

如果你仍然停留在古老的c++ 11中,这段代码将在constexpr上自动后退。如果你用c++ 98/03在洞穴墙壁上作画,noexcept也会被牺牲。

c++ 17更新

在下面的评论中,Lyberta指出新的std::string_view可以取代static_string:

template <class T>
constexpr
std::string_view
type_name()
{
using namespace std;
#ifdef __clang__
string_view p = __PRETTY_FUNCTION__;
return string_view(p.data() + 34, p.size() - 34 - 1);
#elif defined(__GNUC__)
string_view p = __PRETTY_FUNCTION__;
#  if __cplusplus < 201402
return string_view(p.data() + 36, p.size() - 36 - 1);
#  else
return string_view(p.data() + 49, p.find(';', 49) - 49);
#  endif
#elif defined(_MSC_VER)
string_view p = __FUNCSIG__;
return string_view(p.data() + 84, p.size() - 84 - 7);
#endif
}

我已经更新了VS的常数,这要感谢Jive Dadson在下面的评论中非常好的侦探工作。

更新:

一定要看看下面的重写或重写,它们消除了我最新公式中不可读的神奇数字。

我喜欢Nick的方法,一个完整的表单可能是这样的(对于所有基本数据类型):

template <typename T> const char* typeof(T&) { return "unknown"; }    // default
template<> const char* typeof(int&) { return "int"; }
template<> const char* typeof(short&) { return "short"; }
template<> const char* typeof(long&) { return "long"; }
template<> const char* typeof(unsigned&) { return "unsigned"; }
template<> const char* typeof(unsigned short&) { return "unsigned short"; }
template<> const char* typeof(unsigned long&) { return "unsigned long"; }
template<> const char* typeof(float&) { return "float"; }
template<> const char* typeof(double&) { return "double"; }
template<> const char* typeof(long double&) { return "long double"; }
template<> const char* typeof(std::string&) { return "String"; }
template<> const char* typeof(char&) { return "char"; }
template<> const char* typeof(signed char&) { return "signed char"; }
template<> const char* typeof(unsigned char&) { return "unsigned char"; }
template<> const char* typeof(char*&) { return "char*"; }
template<> const char* typeof(signed char*&) { return "signed char*"; }
template<> const char* typeof(unsigned char*&) { return "unsigned char*"; }

一个没有函数重载的更通用的解决方案:

template<typename T>
std::string TypeOf(T){
std::string Type="unknown";
if(std::is_same<T,int>::value) Type="int";
if(std::is_same<T,std::string>::value) Type="String";
if(std::is_same<T,MyClass>::value) Type="MyClass";


return Type;}

这里的MyClass是用户定义的类。这里还可以添加更多的条件。

例子:

#include <iostream>






class MyClass{};




template<typename T>
std::string TypeOf(T){
std::string Type="unknown";
if(std::is_same<T,int>::value) Type="int";
if(std::is_same<T,std::string>::value) Type="String";
if(std::is_same<T,MyClass>::value) Type="MyClass";
return Type;}




int main(){;
int a=0;
std::string s="";
MyClass my;
std::cout<<TypeOf(a)<<std::endl;
std::cout<<TypeOf(s)<<std::endl;
std::cout<<TypeOf(my)<<std::endl;


return 0;}

输出:

int
String
MyClass

你也可以使用c++filt选项-t (type)来要求类型名:

#include <iostream>
#include <typeinfo>
#include <string>


using namespace std;


int main() {
auto x = 1;
string my_type = typeid(x).name();
system(("echo " + my_type + " | c++filt -t").c_str());
return 0;
}

仅在linux上测试。

在c++ 11中,我们有decltype。在标准c++中,没有办法显示使用decltype声明的变量的确切类型。我们可以使用boost typeindex,即type_id_with_cvr (cvr代表const, volatile, reference)来打印如下所示的类型。

#include <iostream>
#include <boost/type_index.hpp>


using namespace std;
using boost::typeindex::type_id_with_cvr;


int main() {
int i = 0;
const int ci = 0;
cout << "decltype(i) is " << type_id_with_cvr<decltype(i)>().pretty_name() << '\n';
cout << "decltype((i)) is " << type_id_with_cvr<decltype((i))>().pretty_name() << '\n';
cout << "decltype(ci) is " << type_id_with_cvr<decltype(ci)>().pretty_name() << '\n';
cout << "decltype((ci)) is " << type_id_with_cvr<decltype((ci))>().pretty_name() << '\n';
cout << "decltype(std::move(i)) is " << type_id_with_cvr<decltype(std::move(i))>().pretty_name() << '\n';
cout << "decltype(std::static_cast<int&&>(i)) is " << type_id_with_cvr<decltype(static_cast<int&&>(i))>().pretty_name() << '\n';
return 0;
}
#include <iostream>
#include <typeinfo>
using namespace std;
#define show_type_name(_t) \
system(("echo " + string(typeid(_t).name()) + " | c++filt -t").c_str())


int main() {
auto a = {"one", "two", "three"};
cout << "Type of a: " << typeid(a).name() << endl;
cout << "Real type of a:\n";
show_type_name(a);
for (auto s : a) {
if (string(s) == "one") {
cout << "Type of s: " << typeid(s).name() << endl;
cout << "Real type of s:\n";
show_type_name(s);
}
cout << s << endl;
}


int i = 5;
cout << "Type of i: " << typeid(i).name() << endl;
cout << "Real type of i:\n";
show_type_name(i);
return 0;
}

输出:

Type of a: St16initializer_listIPKcE
Real type of a:
std::initializer_list<char const*>
Type of s: PKc
Real type of s:
char const*
one
two
three
Type of i: i
Real type of i:
int

当我提出挑战时,我决定测试一下与平台无关的模板技巧能走多远。

名称在编译时完全组装。(这意味着不能使用typeid(T).name(),因此必须显式地为非复合类型提供名称。否则将显示占位符。)

使用示例:

TYPE_NAME(int)
TYPE_NAME(void)
// You probably should list all primitive types here.


TYPE_NAME(std::string)


int main()
{
// A simple case
std::cout << type_name<void(*)(int)> << '\n';
// -> `void (*)(int)`


// Ugly mess case
// Note that compiler removes cv-qualifiers from parameters and replaces arrays with pointers.
std::cout << type_name<void (std::string::*(int[3],const int, void (*)(std::string)))(volatile int*const*)> << '\n';
// -> `void (std::string::*(int *,int,void (*)(std::string)))(volatile int *const*)`


// A case with undefined types
//  If a type wasn't TYPE_NAME'd, it's replaced by a placeholder, one of `class?`, `union?`, `enum?` or `??`.
std::cout << type_name<std::ostream (*)(int, short)> << '\n';
// -> `class? (*)(int,??)`
// With appropriate TYPE_NAME's, the output would be `std::string (*)(int,short)`.
}

代码:

#include <type_traits>
#include <utility>


static constexpr std::size_t max_str_lit_len = 256;


template <std::size_t I, std::size_t N> constexpr char sl_at(const char (&str)[N])
{
if constexpr(I < N)
return str[I];
else
return '\0';
}


constexpr std::size_t sl_len(const char *str)
{
for (std::size_t i = 0; i < max_str_lit_len; i++)
if (str[i] == '\0')
return i;
return 0;
}


template <char ...C> struct str_lit
{
static constexpr char value[] {C..., '\0'};
static constexpr int size = sl_len(value);


template <typename F, typename ...P> struct concat_impl {using type = typename concat_impl<F>::type::template concat_impl<P...>::type;};
template <char ...CC> struct concat_impl<str_lit<CC...>> {using type = str_lit<C..., CC...>;};
template <typename ...P> using concat = typename concat_impl<P...>::type;
};


template <typename, const char *> struct trim_str_lit_impl;
template <std::size_t ...I, const char *S> struct trim_str_lit_impl<std::index_sequence<I...>, S>
{
using type = str_lit<S[I]...>;
};
template <std::size_t N, const char *S> using trim_str_lit = typename trim_str_lit_impl<std::make_index_sequence<N>, S>::type;


#define STR_LIT(str) ::trim_str_lit<::sl_len(str), ::str_lit<STR_TO_VA(str)>::value>
#define STR_TO_VA(str) STR_TO_VA_16(str,0),STR_TO_VA_16(str,16),STR_TO_VA_16(str,32),STR_TO_VA_16(str,48)
#define STR_TO_VA_16(str,off) STR_TO_VA_4(str,0+off),STR_TO_VA_4(str,4+off),STR_TO_VA_4(str,8+off),STR_TO_VA_4(str,12+off)
#define STR_TO_VA_4(str,off) ::sl_at<off+0>(str),::sl_at<off+1>(str),::sl_at<off+2>(str),::sl_at<off+3>(str)


template <char ...C> constexpr str_lit<C...> make_str_lit(str_lit<C...>) {return {};}
template <std::size_t N> constexpr auto make_str_lit(const char (&str)[N])
{
return trim_str_lit<sl_len((const char (&)[N])str), str>{};
}


template <std::size_t A, std::size_t B> struct cexpr_pow {static constexpr std::size_t value = A * cexpr_pow<A,B-1>::value;};
template <std::size_t A> struct cexpr_pow<A,0> {static constexpr std::size_t value = 1;};
template <std::size_t N, std::size_t X, typename = std::make_index_sequence<X>> struct num_to_str_lit_impl;
template <std::size_t N, std::size_t X, std::size_t ...Seq> struct num_to_str_lit_impl<N, X, std::index_sequence<Seq...>>
{
static constexpr auto func()
{
if constexpr (N >= cexpr_pow<10,X>::value)
return num_to_str_lit_impl<N, X+1>::func();
else
return str_lit<(N / cexpr_pow<10,X-1-Seq>::value % 10 + '0')...>{};
}
};
template <std::size_t N> using num_to_str_lit = decltype(num_to_str_lit_impl<N,1>::func());




using spa = str_lit<' '>;
using lpa = str_lit<'('>;
using rpa = str_lit<')'>;
using lbr = str_lit<'['>;
using rbr = str_lit<']'>;
using ast = str_lit<'*'>;
using amp = str_lit<'&'>;
using con = str_lit<'c','o','n','s','t'>;
using vol = str_lit<'v','o','l','a','t','i','l','e'>;
using con_vol = con::concat<spa, vol>;
using nsp = str_lit<':',':'>;
using com = str_lit<','>;
using unk = str_lit<'?','?'>;


using c_cla = str_lit<'c','l','a','s','s','?'>;
using c_uni = str_lit<'u','n','i','o','n','?'>;
using c_enu = str_lit<'e','n','u','m','?'>;


template <typename T> inline constexpr bool ptr_or_ref = std::is_pointer_v<T> || std::is_reference_v<T> || std::is_member_pointer_v<T>;
template <typename T> inline constexpr bool func_or_arr = std::is_function_v<T> || std::is_array_v<T>;


template <typename T> struct primitive_type_name {using value = unk;};


template <typename T, typename = std::enable_if_t<std::is_class_v<T>>> using enable_if_class = T;
template <typename T, typename = std::enable_if_t<std::is_union_v<T>>> using enable_if_union = T;
template <typename T, typename = std::enable_if_t<std::is_enum_v <T>>> using enable_if_enum  = T;
template <typename T> struct primitive_type_name<enable_if_class<T>> {using value = c_cla;};
template <typename T> struct primitive_type_name<enable_if_union<T>> {using value = c_uni;};
template <typename T> struct primitive_type_name<enable_if_enum <T>> {using value = c_enu;};


template <typename T> struct type_name_impl;


template <typename T> using type_name_lit = std::conditional_t<std::is_same_v<typename primitive_type_name<T>::value::template concat<spa>,
typename type_name_impl<T>::l::template concat<typename type_name_impl<T>::r>>,
typename primitive_type_name<T>::value,
typename type_name_impl<T>::l::template concat<typename type_name_impl<T>::r>>;
template <typename T> inline constexpr const char *type_name = type_name_lit<T>::value;


template <typename T, typename = std::enable_if_t<!std::is_const_v<T> && !std::is_volatile_v<T>>> using enable_if_no_cv = T;


template <typename T> struct type_name_impl
{
using l = typename primitive_type_name<T>::value::template concat<spa>;
using r = str_lit<>;
};
template <typename T> struct type_name_impl<const T>
{
using new_T_l = std::conditional_t<type_name_impl<T>::l::size && !ptr_or_ref<T>,
spa::concat<typename type_name_impl<T>::l>,
typename type_name_impl<T>::l>;
using l = std::conditional_t<ptr_or_ref<T>,
typename new_T_l::template concat<con>,
con::concat<new_T_l>>;
using r = typename type_name_impl<T>::r;
};
template <typename T> struct type_name_impl<volatile T>
{
using new_T_l = std::conditional_t<type_name_impl<T>::l::size && !ptr_or_ref<T>,
spa::concat<typename type_name_impl<T>::l>,
typename type_name_impl<T>::l>;
using l = std::conditional_t<ptr_or_ref<T>,
typename new_T_l::template concat<vol>,
vol::concat<new_T_l>>;
using r = typename type_name_impl<T>::r;
};
template <typename T> struct type_name_impl<const volatile T>
{
using new_T_l = std::conditional_t<type_name_impl<T>::l::size && !ptr_or_ref<T>,
spa::concat<typename type_name_impl<T>::l>,
typename type_name_impl<T>::l>;
using l = std::conditional_t<ptr_or_ref<T>,
typename new_T_l::template concat<con_vol>,
con_vol::concat<new_T_l>>;
using r = typename type_name_impl<T>::r;
};
template <typename T> struct type_name_impl<T *>
{
using l = std::conditional_t<func_or_arr<T>,
typename type_name_impl<T>::l::template concat<lpa, ast>,
typename type_name_impl<T>::l::template concat<     ast>>;
using r = std::conditional_t<func_or_arr<T>,
rpa::concat<typename type_name_impl<T>::r>,
typename type_name_impl<T>::r>;
};
template <typename T> struct type_name_impl<T &>
{
using l = std::conditional_t<func_or_arr<T>,
typename type_name_impl<T>::l::template concat<lpa, amp>,
typename type_name_impl<T>::l::template concat<     amp>>;
using r = std::conditional_t<func_or_arr<T>,
rpa::concat<typename type_name_impl<T>::r>,
typename type_name_impl<T>::r>;
};
template <typename T> struct type_name_impl<T &&>
{
using l = std::conditional_t<func_or_arr<T>,
typename type_name_impl<T>::l::template concat<lpa, amp, amp>,
typename type_name_impl<T>::l::template concat<     amp, amp>>;
using r = std::conditional_t<func_or_arr<T>,
rpa::concat<typename type_name_impl<T>::r>,
typename type_name_impl<T>::r>;
};
template <typename T, typename C> struct type_name_impl<T C::*>
{
using l = std::conditional_t<func_or_arr<T>,
typename type_name_impl<T>::l::template concat<lpa, type_name_lit<C>, nsp, ast>,
typename type_name_impl<T>::l::template concat<     type_name_lit<C>, nsp, ast>>;
using r = std::conditional_t<func_or_arr<T>,
rpa::concat<typename type_name_impl<T>::r>,
typename type_name_impl<T>::r>;
};
template <typename T> struct type_name_impl<enable_if_no_cv<T[]>>
{
using l = typename type_name_impl<T>::l;
using r = lbr::concat<rbr, typename type_name_impl<T>::r>;
};
template <typename T, std::size_t N> struct type_name_impl<enable_if_no_cv<T[N]>>
{
using l = typename type_name_impl<T>::l;
using r = lbr::concat<num_to_str_lit<N>, rbr, typename type_name_impl<T>::r>;
};
template <typename T> struct type_name_impl<T()>
{
using l = typename type_name_impl<T>::l;
using r = lpa::concat<rpa, typename type_name_impl<T>::r>;
};
template <typename T, typename P1, typename ...P> struct type_name_impl<T(P1, P...)>
{
using l = typename type_name_impl<T>::l;
using r = lpa::concat<type_name_lit<P1>,
com::concat<type_name_lit<P>>..., rpa, typename type_name_impl<T>::r>;
};


#define TYPE_NAME(t) template <> struct primitive_type_name<t> {using value = STR_LIT(#t);};

正如Scott Meyers在有效的现代c++中所解释的那样,

std::type_info::name的调用不能保证返回任何有意义的东西。

最好的解决方案是让编译器在类型推断期间生成错误消息,例如:

template<typename T>
class TD;


int main(){
const int theAnswer = 32;
auto x = theAnswer;
auto y = &theAnswer;
TD<decltype(x)> xType;
TD<decltype(y)> yType;
return 0;
}

根据不同的编译器,结果会是这样的:

test4.cpp:10:21: error: aggregate ‘TD<int> xType’ has incomplete type and cannot be defined TD<decltype(x)> xType;


test4.cpp:11:21: error: aggregate ‘TD<const int *> yType’ has incomplete type and cannot be defined TD<decltype(y)> yType;

因此,我们知道x的类型是inty的类型是const int*

根据霍华德的解决方案,如果你不喜欢神奇的数字,我认为这是一个很好的表示方式,它看起来很直观:

#include <string_view>


template <typename T>
constexpr auto type_name() {
std::string_view name, prefix, suffix;
#ifdef __clang__
name = __PRETTY_FUNCTION__;
prefix = "auto type_name() [T = ";
suffix = "]";
#elif defined(__GNUC__)
name = __PRETTY_FUNCTION__;
prefix = "constexpr auto type_name() [with T = ";
suffix = "]";
#elif defined(_MSC_VER)
name = __FUNCSIG__;
prefix = "auto __cdecl type_name<";
suffix = ">(void)";
#endif
name.remove_prefix(prefix.size());
name.remove_suffix(suffix.size());
return name;
}

Demo.

霍华德Hinnant使用魔术数字提取类型名称。康桓瑋建议字符串前缀和后缀。但是前缀/后缀一直在变化。 使用" probe_type " type_name自动计算" probe_type "的前缀和后缀大小以提取类型名称:

#include <string_view>
using namespace std;


namespace typeName {
template <typename T>
constexpr string_view wrapped_type_name () {
#ifdef __clang__
return __PRETTY_FUNCTION__;
#elif defined(__GNUC__)
return  __PRETTY_FUNCTION__;
#elif defined(_MSC_VER)
return  __FUNCSIG__;
#endif
}


class probe_type;
constexpr string_view probe_type_name ("typeName::probe_type");
constexpr string_view probe_type_name_elaborated ("class typeName::probe_type");
constexpr string_view probe_type_name_used (wrapped_type_name<probe_type> ().find (probe_type_name_elaborated) != -1 ? probe_type_name_elaborated : probe_type_name);


constexpr size_t prefix_size () {
return wrapped_type_name<probe_type> ().find (probe_type_name_used);
}


constexpr size_t suffix_size () {
return wrapped_type_name<probe_type> ().length () - prefix_size () - probe_type_name_used.length ();
}


template <typename T>
string_view type_name () {
constexpr auto type_name = wrapped_type_name<T> ();


return type_name.substr (prefix_size (), type_name.length () - prefix_size () - suffix_size ());
}
}


#include <iostream>


using typeName::type_name;
using typeName::probe_type;


class test;


int main () {
cout << type_name<class test> () << endl;


cout << type_name<const int*&> () << endl;
cout << type_name<unsigned int> () << endl;


const int ic = 42;
const int* pic = &ic;
const int*& rpic = pic;
cout << type_name<decltype(ic)> () << endl;
cout << type_name<decltype(pic)> () << endl;
cout << type_name<decltype(rpic)> () << endl;


cout << type_name<probe_type> () << endl;
}

输出

# EYZ0:

test
const int *&
unsigned int
const int
const int *
const int *&
typeName::probe_type

# EYZ0:

test
const int *&
unsigned int
const int
const int *
const int *&
typeName::probe_type

VS 2019版本16.7.6:

class test
const int*&
unsigned int
const int
const int*
const int*&
class typeName::probe_type

对于那些还在访问的人,我最近也遇到了同样的问题,并决定根据这篇文章的答案编写一个小型库。它提供了constexpr类型名称和类型索引,并且在Mac, Windows和Ubuntu上进行了测试。

库代码在这里:https://github.com/TheLartians/StaticTypeInfo

另一个采取@康桓瑋的答案(原来),对前缀和后缀细节的假设较少,并受到@ val的答案 -但没有污染全局名称空间;无条件的:没有任何条件的;希望更容易阅读。

流行的编译器提供了带有当前函数签名的宏。现在,函数是可模板化的;因此签名包含模板参数。因此,基本的方法是:给定一个类型,在函数中使用该类型作为模板参数。

不幸的是,类型名称被包装在描述函数的文本中,这在不同的编译器中是不同的。例如,在GCC中,类型为doubletemplate <typename T> int foo()的签名是:int foo() [T = double]

那么,如何消除包装器文本呢?@HowardHinnant的解决方案是最短和最“直接”的:只需使用每个编译器的魔法数字来删除前缀和后缀。但显然,这是非常脆弱的;没有人喜欢在代码中加入神奇的数字。然而,事实证明,给定具有已知名称的类型的宏值,您可以确定构成包装的前缀和后缀。

#include <string_view>


template <typename T> constexpr std::string_view type_name();


template <>
constexpr std::string_view type_name<void>()
{ return "void"; }


namespace detail {


using type_name_prober = void;


template <typename T>
constexpr std::string_view wrapped_type_name()
{
#ifdef __clang__
return __PRETTY_FUNCTION__;
#elif defined(__GNUC__)
return __PRETTY_FUNCTION__;
#elif defined(_MSC_VER)
return __FUNCSIG__;
#else
#error "Unsupported compiler"
#endif
}


constexpr std::size_t wrapped_type_name_prefix_length() {
return wrapped_type_name<type_name_prober>().find(type_name<type_name_prober>());
}


constexpr std::size_t wrapped_type_name_suffix_length() {
return wrapped_type_name<type_name_prober>().length()
- wrapped_type_name_prefix_length()
- type_name<type_name_prober>().length();
}


} // namespace detail


template <typename T>
constexpr std::string_view type_name() {
constexpr auto wrapped_name = detail::wrapped_type_name<T>();
constexpr auto prefix_length = detail::wrapped_type_name_prefix_length();
constexpr auto suffix_length = detail::wrapped_type_name_suffix_length();
constexpr auto type_name_length = wrapped_name.length() - prefix_length - suffix_length;
return wrapped_name.substr(prefix_length, type_name_length);
}

< kbd > GodBolt < / kbd >上看到。这应该与MSVC工作以及。

复制这个答案:https://stackoverflow.com/a/56766138/11502722

我能够得到这个有些工作的c++ static_assert()。这里的问题是static_assert()只接受字符串字面量;constexpr string_view行不通。你需要接受typename周围的额外文本,但它可以工作:

template<typename T>
constexpr void assertIfTestFailed()
{
#ifdef __clang__
static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);
#elif defined(__GNUC__)
static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);
#elif defined(_MSC_VER)
static_assert(testFn<T>(), "Test failed on this used type: " __FUNCSIG__);
#else
static_assert(testFn<T>(), "Test failed on this used type (see surrounding logged error for details).");
#endif
}
}

MSVC输出:

error C2338: Test failed on this used type: void __cdecl assertIfTestFailed<class BadType>(void)
... continued trace of where the erroring code came from ...

有些不同,这里有一个“To english”;类型的转换,解构每个限定符、范围、参数等等,递归地构建描述类型的字符串,我认为&;演绎了this&;提案将有助于减少许多专门化。无论如何,这是一个有趣的晨练,尽管过度膨胀。:)

struct X {
using T = int *((*)[10]);
T f(T, const unsigned long long * volatile * );
};


int main() {


std::cout << describe<decltype(&X::f)>() << std::endl;
}

输出:

pointer to member function of class 1X taking (pointer to array[10]
of pointer to int, pointer to volatile pointer to const unsigned
long long), and returning pointer to array[10] of pointer to int
下面是代码: # EYZ0 < / p >

请注意:最新版本在我的github: https://github.com/cuzdav/type_to_string

// Print types as strings, including functions, member


#include <type_traits>
#include <typeinfo>
#include <string>
#include <utility>


namespace detail {


template <typename T> struct Describe;


template <typename T, class ClassT>
struct Describe<T (ClassT::*)>  {
static std::string describe();
};
template <typename RetT, typename... ArgsT>
struct Describe<RetT(ArgsT...)>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...)>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) const>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) volatile>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) noexcept>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) const volatile>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) const noexcept>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) volatile noexcept>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) const volatile noexcept>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...)&>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) const &>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) volatile &>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) & noexcept>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) const volatile &>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) const & noexcept>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) volatile & noexcept>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) const volatile & noexcept>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) &&>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) const &&>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) volatile &&>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) && noexcept>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) const volatile &&>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) const && noexcept>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) volatile && noexcept>  {
static std::string describe();
};
template <typename RetT, class ClassT, typename... ArgsT>
struct Describe<RetT(ClassT::*)(ArgsT...) const volatile && noexcept>  {
static std::string describe();
};


template <typename T>
std::string describe()
{
using namespace std::string_literals;
auto terminal = [&](char const * desc) {
return desc + " "s + typeid(T).name();
};
if constexpr(std::is_const_v<T>) {
return "const " + describe<std::remove_const_t<T>>();
}
else if constexpr(std::is_volatile_v<T>) {
return "volatile " + describe<std::remove_volatile_t<T>>();
}
else if constexpr (std::is_same_v<bool, T>) {
return "bool";
}
else if constexpr(std::is_same_v<char, T>) {
return "char";
}
else if constexpr(std::is_same_v<signed char, T>) {
return "signed char";
}
else if constexpr(std::is_same_v<unsigned char, T>) {
return "unsigned char";
}
else if constexpr(std::is_unsigned_v<T>) {
return "unsigned " + describe<std::make_signed_t<T>>();
}
else if constexpr(std::is_void_v<T>) {
return "void";
}
else if constexpr(std::is_integral_v<T>) {
if constexpr(std::is_same_v<short, T>)
return "short";
else if constexpr(std::is_same_v<int, T>)
return "int";
else if constexpr(std::is_same_v<long, T>)
return "long";
else if constexpr(std::is_same_v<long long, T>)
return "long long";
}
else if constexpr(std::is_same_v<float, T>) {
return "float";
}
else if constexpr(std::is_same_v<double, T>) {
return "double";
}
else if constexpr(std::is_same_v<long double, T>) {
return "long double";
}
else if constexpr(std::is_same_v<std::nullptr_t, T>) {
return "nullptr_t";
}
else if constexpr(std::is_class_v<T>) {
return terminal("class");
}
else if constexpr(std::is_union_v<T>) {
return terminal("union");
}
else if constexpr(std::is_enum_v<T>) {
std::string result;
if (!std::is_convertible_v<T, std::underlying_type_t<T>>) {
result += "scoped ";
}
return result + terminal("enum");
}
else if constexpr(std::is_pointer_v<T>) {
return "pointer to " + describe<std::remove_pointer_t<T>>();
}
else if constexpr(std::is_lvalue_reference_v<T>) {
return "lvalue-ref to " + describe<std::remove_reference_t<T>>();
}
else if constexpr(std::is_rvalue_reference_v<T>) {
return "rvalue-ref to " + describe<std::remove_reference_t<T>>();
}
else if constexpr(std::is_bounded_array_v<T>) {
return "array[" + std::to_string(std::extent_v<T>) + "] of " +
describe<std::remove_extent_t<T>>();
}
else if constexpr(std::is_unbounded_array_v<T>) {
return "array[] of " + describe<std::remove_extent_t<T>>();
}
else if constexpr(std::is_function_v<T>) {
return Describe<T>::describe();
}
else if constexpr(std::is_member_object_pointer_v<T>) {
return Describe<T>::describe();
}
else if constexpr(std::is_member_function_pointer_v<T>) {
return Describe<T>::describe();
}
}


template <typename RetT, typename... ArgsT>
std::string Describe<RetT(ArgsT...)>::describe() {
std::string result = "function taking (";
((result += detail::describe<ArgsT>(", ")), ...);
return result + "), returning " + detail::describe<RetT>();
}


template <typename T, class ClassT>
std::string Describe<T (ClassT::*)>::describe() {
return "pointer to member of " + detail::describe<ClassT>() +
" of type " + detail::describe<T>();
}


struct Comma {
char const * sep = "";
std::string operator()(std::string const& str) {
return std::exchange(sep, ", ") + str;
}
};
enum Qualifiers {NONE=0, CONST=1, VOLATILE=2, NOEXCEPT=4, LVREF=8, RVREF=16};


template <typename RetT, typename ClassT, typename... ArgsT>
std::string describeMemberPointer(Qualifiers q) {
std::string result = "pointer to ";
if (NONE != (q & CONST)) result += "const ";
if (NONE != (q & VOLATILE)) result += "volatile ";
if (NONE != (q & NOEXCEPT)) result += "noexcept ";
if (NONE != (q & LVREF)) result += "lvalue-ref ";
if (NONE != (q & RVREF)) result += "rvalue-ref ";
result += "member function of " + detail::describe<ClassT>() + " taking (";
Comma comma;
((result += comma(detail::describe<ArgsT>())), ...);
return result + "), and returning " + detail::describe<RetT>();
}


template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...)>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(NONE);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) const>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(CONST);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) noexcept>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(NOEXCEPT);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) volatile>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(VOLATILE);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) volatile noexcept>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(VOLATILE | NOEXCEPT);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) const volatile>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(CONST | VOLATILE);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) const noexcept>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(CONST | NOEXCEPT);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) const volatile noexcept>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(CONST | VOLATILE | NOEXCEPT);
}


template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) &>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) const &>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | CONST);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) & noexcept>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | NOEXCEPT);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) volatile &>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | VOLATILE);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) volatile & noexcept>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | VOLATILE | NOEXCEPT);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) const volatile &>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | CONST | VOLATILE);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) const & noexcept>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | CONST | NOEXCEPT);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) const volatile & noexcept>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | CONST | VOLATILE | NOEXCEPT);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...)&&>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) const &&>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | CONST);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) && noexcept>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | NOEXCEPT);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) volatile &&>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | VOLATILE);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) volatile && noexcept>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | VOLATILE | NOEXCEPT);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) const volatile &&>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | CONST | VOLATILE);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) const && noexcept>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | CONST | NOEXCEPT);
}
template <typename RetT, class ClassT, typename... ArgsT>
std::string Describe<RetT(ClassT::*)(ArgsT...) const volatile && noexcept>::describe() {
return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | CONST | VOLATILE | NOEXCEPT);
}


} // detail


///////////////////////////////////
// Main function
///////////////////////////////////
template <typename T>
std::string describe() {
return detail::describe<T>();
}




///////////////////////////////////
// Sample code
///////////////////////////////////
#include <iostream>




struct X {
using T = int *((*)[10]);
T f(T, const unsigned long long * volatile * );
};


int main() {
std::cout << describe<decltype(&X::f)>() << std::endl;
}


基于之前的一些答案,我做出了这个解决方案,它不将__PRETTY_FUNCTION__的结果存储在二进制文件中。它使用静态数组保存类型名称的字符串表示形式。

它需要c++ 23。

#include <iostream>
#include <string_view>
#include <array>


template <typename T>
constexpr auto type_name() {
auto gen = [] <class R> () constexpr -> std::string_view  {
return __PRETTY_FUNCTION__;
};
constexpr std::string_view search_type = "float";
constexpr auto search_type_string = gen.template operator()<float>();
constexpr auto prefix = search_type_string.find(search_type);
constexpr auto suffix = search_type_string.size() - prefix - search_type.size();
constexpr auto str = gen.template operator()<T>();
constexpr int size = str.size() - prefix - suffix;
constexpr auto static arr = [&]<std::size_t... I>(std::index_sequence<I...>) constexpr {
return std::array<char, size>{str[prefix + I]...};
} (std::make_index_sequence<size>{});


return std::string_view(arr.data(), size);
}

c++在编译时使用模板和运行时使用TypeId进行数据类型解析。

编译时解决方案。

template <std::size_t...Idxs>
constexpr auto substring_as_array(std::string_view str, std::index_sequence<Idxs...>)
{
return std::array{str[Idxs]..., '\n'};
}


template <typename T>
constexpr auto type_name_array()
{
#if defined(__clang__)
constexpr auto prefix   = std::string_view{"[T = "};
constexpr auto suffix   = std::string_view{"]"};
constexpr auto function = std::string_view{__PRETTY_FUNCTION__};
#elif defined(__GNUC__)
constexpr auto prefix   = std::string_view{"with T = "};
constexpr auto suffix   = std::string_view{"]"};
constexpr auto function = std::string_view{__PRETTY_FUNCTION__};
#elif defined(_MSC_VER)
constexpr auto prefix   = std::string_view{"type_name_array<"};
constexpr auto suffix   = std::string_view{">(void)"};
constexpr auto function = std::string_view{__FUNCSIG__};
#else
# error Unsupported compiler
#endif


constexpr auto start = function.find(prefix) + prefix.size();
constexpr auto end = function.rfind(suffix);


static_assert(start < end);


constexpr auto name = function.substr(start, (end - start));
return substring_as_array(name, std::make_index_sequence<name.size()>{});
}


template <typename T>
struct type_name_holder {
static inline constexpr auto value = type_name_array<T>();
};


template <typename T>
constexpr auto type_name() -> std::string_view
{
constexpr auto& value = type_name_holder<T>::value;
return std::string_view{value.data(), value.size()};
}

运行时的解决方案。

template <typename T>
void PrintDataType(T type)
{
auto name = typeid(type).name();
string cmd_str = "echo '" + string(name) + "' | c++filt -t";
system(cmd_str.c_str());
}

主要代码

#include <iostream>
#include <map>
#include <string>
#include <typeinfo>
#include <string_view>
#include <array>   // std::array
#include <utility> // std::index_sequence
using std::string;
int main()
{
//Dynamic resolution.
std::map<int, int> iMap;
PrintDataType(iMap);
    

//Compile type resolution.
std::cout << type_name<std::list<int>>() << std::endl;


return 0;
}

代码片段

考虑下面的代码:

#include <iostream>


int main()
{
int a = 2; // Declare type "int"
std::string b = "Hi"; // Declare type "string"
long double c = 3438; // Declare type "long double"
if(typeid(a) == typeid(int))
{
std::cout<<"int\n";
}


if(typeid(b) == typeid(std::string))
{
std::cout<<"string\n";
}
    

if(typeid(c) == typeid(long double))
{
std::cout<<"long double";
}
return 0;
}

我相信你想要整个单词(而不是只打印int的缩写形式(即i),你想要int),这就是为什么我做了if

对于一些变量(stringlong double等…)比较它们的简短形式,它们不会输出预期的结果),您需要比较应用typeid操作符的结果与特定类型的typeid操作符的结果。

从cppreference:

返回一个实现定义的以空结束的字符串,包含类型的名称。不提供任何保证;特别地,返回的字符串对于多个类型是相同的,并且在同一个程序的调用之间会发生变化。


在我看来,Python在这种情况下比c++更好。Python有内置的type函数来直接访问变量的数据类型。