demangled_names.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2013-2019 Antony Polukhin
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See the accompanying file LICENSE_1_0.txt
  4. // or a copy at <http://www.boost.org/LICENSE_1_0.txt>.)
  5. //[type_index_names_example
  6. /*`
  7. The following example shows how short (mangled) and human readable type names could be obtained from a type.
  8. Works with and without RTTI.
  9. */
  10. #include <boost/type_index.hpp>
  11. #include <iostream>
  12. template <class T>
  13. void foo(T) {
  14. std::cout << "\n Short name: " << boost::typeindex::type_id<T>().raw_name();
  15. std::cout << "\n Readable name: " << boost::typeindex::type_id<T>().pretty_name();
  16. }
  17. struct user_defined_type{};
  18. namespace ns1 { namespace ns2 {
  19. struct user_defined_type{};
  20. }} // namespace ns1::ns2
  21. namespace {
  22. struct in_anon_type{};
  23. } // anonymous namespace
  24. int main() {
  25. // Call to
  26. foo(1);
  27. // will output something like this:
  28. //
  29. // (RTTI on) (RTTI off)
  30. // Short name: i Short name: int]
  31. // Readable name: int Readable name: int
  32. user_defined_type t;
  33. foo(t);
  34. // Will output:
  35. //
  36. // (RTTI on) (RTTI off)
  37. // Short name: 17user_defined_type user_defined_type]
  38. // Readable name: user_defined_type user_defined_type
  39. ns1::ns2::user_defined_type t_in_ns;
  40. foo(t_in_ns);
  41. // Will output:
  42. //
  43. // (RTTI on) (RTTI off)
  44. // Short name: N3ns13ns217user_defined_typeE ns1::ns2::user_defined_type]
  45. // Readable name: ns1::ns2::user_defined_type ns1::ns2::user_defined_type
  46. in_anon_type anon_t;
  47. foo(anon_t);
  48. // Will output:
  49. //
  50. // (RTTI on) (RTTI off)
  51. // Short name: N12_GLOBAL__N_112in_anon_typeE {anonymous}::in_anon_type]
  52. // Readable name: (anonymous namespace)::in_anon_type {anonymous}::in_anon_type
  53. }
  54. /*`
  55. Short names are very compiler dependant: some compiler will output `.H`, others `i`.
  56. Readable names may also differ between compilers: `struct user_defined_type`, `user_defined_type`.
  57. [warning With RTTI off different classes with same names in anonymous namespace may collapse. See 'RTTI emulation limitations'. ]
  58. */
  59. //] [/type_index_names_example]