Retrieving a c++ class name programmatically

前端 未结 5 1829
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:49

    With C++17, and a third-party library, you can now obtain the name of a class like

    #include 
    #include "nameof.hpp"
    
    namespace test {
        class Object {};
    }
    
    int main() {
        constexpr auto obj_name = nameof::nameof_type();
        std::cout << obj_name << std::endl;
        // this prints "test::Object"
    }
    

    This uses only compile-time information, so it can be constexpr. Note that it’s not portable; for example Intel’s compiler isn’t supported.

提交回复
热议问题