5

I need to print the name of a class such as

template<typename... Args>
struct S{};

Using typeid(S<int,std::vector<double>>).name() its fairly simple to print something representative. With boost demangle it might even be readable on gcc.

Is there any way to get the name so the name is the same between different compilers?

Bomaz
  • 1,871
  • 1
  • 17
  • 22

3 Answers3

3

Not really. The mangled name is, in general, compiler-specific. See the table titled "How different compilers mangle the same functions" on Wikipedia

Marshall Clow
  • 15,972
  • 2
  • 29
  • 45
1

No. There is no portable way to get the name as a string for an arbitrary type across all platforms.

You can potentially write a function template that uses platform-specific code to determine a name of a template parameter, but that is tricky to do, and brittle.

Alternatively, if you only want names for your types, or you are willing to register names for every type that you need a name for, then you can do something like:

some_library::register_type_name<some_type>("some_type");
some_library::register_type_name<some_other_type>("some_other_type");

adding entries to an internal map of typeid to string. This could be hidden behind a macro like REGISTER_TYPE(x), but it would still need to be done for every type.

You can then easily write some_library::lookup_type_name<some_type>() which searches the registered types and returns the string. You could also write an overload especially for S which looked up the name of its template parameters too.

Anthony Williams
  • 66,628
  • 14
  • 133
  • 155
-1

You could write a library that provides a name for all standard types, plus containers of standard types, plus make it extensible for project specific types ...

That's exactly what the "type name" sub-library in Celma does.

See examples of the usage in the test file: https://github.com/Gemini67/Celma/blob/master/src/library/common/test/test_type_name.cpp

The starting point for the whole library is here: https://github.com/Gemini67/Celma

Rene
  • 2,466
  • 1
  • 12
  • 18
  • I don't think thats possible to do for all combinations of arguments that could occur in the example provided – Bomaz Nov 15 '19 at 15:15
  • @Bomaz It is. The library can handle std::tuple too, which uses exactly this kind of interface. – Rene Nov 15 '19 at 15:18
  • Does it handle user defined, templated, types as in the example? That would be very useful – Bomaz Nov 15 '19 at 15:19
  • @Bomaz Not automatically, but it is possible to define the necessary partial template specialisation for user-defined types, templated or not. – Rene Nov 15 '19 at 15:20