How to get C++ object name in run time?

前端 未结 8 1128
失恋的感觉
失恋的感觉 2021-01-17 11:08

Can I get an object\'s name in run time (like getting an object\'s type via RTTI)? I want the object to be able to print its name.

相关标签:
8条回答
  • 2021-01-17 12:12

    Since objects in C++ don't have any names, you cannot get them. The only thing you can get to identify an object is its address.

    Otherwise, you can implement your naming scheme (which means the objects would have some char* or std::string member with their name). You can inspire yourself in Qt with their QObject hierarchy, which uses a similar approach.

    0 讨论(0)
  • 2021-01-17 12:12

    This may be GCC-specific:

    #include <typeinfo>
    #include <iostream>
    
    template <typename T>
    void foo(T t)
    {
        std::cout << typeid(t).name() << std::endl;
    }
    
    0 讨论(0)
提交回复
热议问题