c++reflectionc++17type-erasureboost-any

How do I get the name of the type currently held by an `any`?


Suppose I have either:

  1. A boost::any or
  2. An std::any (and I'm using C++17)

the type of which I don't know. Is it possible for me to print, or get as a string, the name of the type that's being held by the any?

Note: Even a mangled type name - the kind you get with typeid(TR).name() - would be sufficient I can take it from there using abi::__cxa_demangle.


Solution

  • #include <any>
    #include <iostream>
    using namespace std;
    
    namespace TestNamespace {
      class Test {
        int x{ 0 };
        int y{ 1 };
      };
    }
    
    int main()
    {       
      any thing = TestNamespace::Test();
    
      cout << thing.type().name() << endl;
      cin.get();
    
      return 0;
    }
    

    Output: class TestNamespace::Test

    Oh and at least in msvc, the type_info for a std template library class looks a lot uglier than say std::string (looks like: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)