开发者

Getting a string representation of a template parameter

I wan开发者_运维问答t to be able to create a method in a templated class that returns the name of the type subsituted in the template parameter.

eg:

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

This is possible with a preprocessor macro using #, I figured there must be a way with templates.

Is this possible?


You can use typeid(T).name(), though it will return decorated name of the type.

If you're using GCC, then you can use GCC API, declared incxxabi.h header, to demangle the names.

Here is an example (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;
}

Output:

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

Another interesting link that describe demangling in GCC and Microsoft VC++:

  • C++ Name Mangling/Demangling
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜