获取模板参数的字符串表示形式

时间:2011-09-25 12:07:11

标签: c++ templates

我希望能够在模板化类中创建一个方法,该方法返回模板参数中替换的类型的名称。

例如:

template <typename T>
class CPropertyValueT 
{
  std::string GetTypeName()
  {
    return #T;
  }
}

使用#的预处理器宏可以实现这一点,我认为必须有模板的方法。

这可能吗?

2 个答案:

答案 0 :(得分:6)

您可以使用typeid(T).name(),但它会返回该类型的装饰名称。

如果您正在使用GCC,那么您可以使用cxxabi.h标题中声明的GCC API来解码名称。

以下是一个示例(source):

#include <exception>
#include <iostream>
#include <cxxabi.h>

struct empty { };

template <typename T, int N>
  struct bar { };


int main()
{
  int     status;
  char   *realname;

  // exception classes not in <stdexcept>, thrown by the implementation
  // instead of the user
  std::bad_exception  e;
  realname = abi::__cxa_demangle(e.what(), 0, 0, &status);
  std::cout << e.what() << "\t=> " << realname << "\t: " << status << '\n';
  free(realname);


  // typeid
  bar<empty,17>          u;
  const std::type_info  &ti = typeid(u);

  realname = abi::__cxa_demangle(ti.name(), 0, 0, &status);
  std::cout << ti.name() << "\t=> " << realname << "\t: " << status << '\n';
  free(realname);

  return 0;
}

输出:

  St13bad_exception       => std::bad_exception   : 0
  3barI5emptyLi17EE       => bar<empty, 17>       : 0

另一个描述GCC和Microsoft VC ++中的解码的有趣链接:

答案 1 :(得分:0)

#include <cstdlib>
#include <typeinfo>
#include <iostream>

using namespace std;

template <typename T>
class CPropertyValueT 
{
public:
  std::string GetTypeName()
  {
    return std::string(typeid(T).name());
  }
};

int main()
{
    CPropertyValueT<float> x;

    cout << x.GetTypeName();

    return 0;
}
相关问题