3

In C++, is it possible to get the name of a type alias ?

For instance:

using my_type = some_type<a,b,c>;
std::cout << get_type_name<my_type>() << std::endl;

Would print my_type, not some_type<a,b,c>.

nicoulaj
  • 3,463
  • 4
  • 27
  • 32
  • 7
    [I have a feeling you ask because you think it will solve another problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – StoryTeller - Unslander Monica Jan 13 '18 at 17:02
  • 2
    Typically it's not possibly to get *any* names of *any* type. The [`std::type_info::name`](http://en.cppreference.com/w/cpp/types/type_info/name) function (which is the only standard and portable way to get any kind of "name" of a type) is not guaranteed to give a nice name. – Some programmer dude Jan 13 '18 at 17:07
  • 1
    To be honest my use case is just tracing/debugging utilities, I was wondering if there was some magic to do this. – nicoulaj Jan 13 '18 at 17:14
  • `using` and `typedef` do not generate new types, you need to inherit to generate a truly new type: `struct my_type : public some_type {};` – rustyx Jan 13 '18 at 18:07
  • Possible duplicate of [C++ Strongly typed using and typedef](https://stackoverflow.com/questions/34287842/c-strongly-typed-using-and-typedef) – rustyx Jan 13 '18 at 18:08
  • @RustyX: Public inheritance defeats the purpose of increasing type safety. You should use private inheritance instead, and delegate member functions where necessary. – Christian Hackl Jan 13 '18 at 18:10
  • Note that Boost TypeIndex is able to get nicely formatted type names, but not of their aliases. It might be convenient, e.g., for development of template metafunctions or when just learning stuff like perfect forwarding. – Daniel Langr Jan 13 '18 at 18:13

1 Answers1

3

No, you cannot, barring stringifying macros (which has nothing to do with type system).

There are ways to do strong typedefs, but they generate new types.

Note that the name on a typeid need not be human readable or even unique.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524