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

前端 未结 8 1142
失恋的感觉
失恋的感觉 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:08

    So, this is basically what I did. It's hacky, but it does the trick. I created a variadic macro that takes advantage of stringizing. Unfortunately, it becomes clumsy with the need for a _dummy parameter in order to provide the pseudo-default ctor, because you cannot omit the comma separating the named argument from the variable arguments (I even tried with gnu cpp, but was unsucessful--may I didn't try hard enough).

    #include 
    
    #define MyNamedClass( objname, ... ) MyClass objname(__VA_ARGS__, #objname )
    
    class MyClass
    {
    public:
       MyClass( void* _dummy=nullptr, const std::string& _name="anonymous") : name( _name ) {}
       MyClass( int i, const std::string& _name="anonymous" ) : name( _name ) {}
    
    private:
       std::string name;
    };
    
    
    int main()
    {
       MyClass mc0;
       MyClass mc1(54321);
       MyNamedClass( mc2, nullptr);
       MyNamedClass( mc3, 12345 );
    
       return 0;
    }
    

提交回复
热议问题