3

I want 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?

Spencer Rose
  • 1,190
  • 12
  • 21

1 Answers1

6

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++:

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Good answer, this is the best one can do. However, it is noteworthy that `name()` isn't mandated to return anything meaningful by the standard, so it's a QOI issue. – Armen Tsirunyan Sep 25 '11 at 12:15
  • @ArmenTsirunyan: Yes. BTW, I added more stuffs to my answer. – Nawaz Sep 25 '11 at 12:20