Retrieving a c++ class name programmatically

前端 未结 5 1823
Happy的楠姐
Happy的楠姐 2020-12-04 13:23

I was wondering if it is possible in C++ to retrieve the name of a class in string form without having to hardcode it into a variable or a getter. I\'m aware that none of th

5条回答
  •  死守一世寂寞
    2020-12-04 13:41

    You can use typeid:

    #include 
    
    std::cout << typeid(obj).name() << "\n";
    

    However, the type name isn't standardided and may differ between different compilers (or even different versions of the same compiler), and it is generally not human readable because it is mangled.

    On GCC and clang (with libstdc++ and libc++), you can demangle names using the __cxa_demangle function (on MSVC demangling does not seem necessary):

    #include 
    #include 
    #include 
    #include 
    
    std::string demangle(char const* mangled) {
        auto ptr = std::unique_ptr{
            abi::__cxa_demangle(mangled, nullptr, nullptr, nullptr),
            std::free
        };
        return {ptr.get()};
    }
    

    This will still not necessarily be a readable name — for instance, std::string is a type name for the actual type, and its complete type name in the current libstdc++ is std::__cxx11::basic_string, std::allocator >; by contrast, in the current libc++ it’s std::__1::basic_string, std::__1::allocator >. “Prettifying” type aliases is unfortunately not trivial.

提交回复
热议问题