Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a string representation of a template parameter

Tags:

c++

templates

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?

like image 323
Spencer Rose Avatar asked Oct 16 '25 13:10

Spencer Rose


1 Answers

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
like image 139
Nawaz Avatar answered Oct 19 '25 13:10

Nawaz