generic way to print out variable name in c++

前端 未结 6 789
难免孤独
难免孤独 2020-12-05 20:47

given a class

struct {
  int a1;
  bool a2;
  ...
  char* a500;
  ...
  char a10000;      
}

I want to print or stream out



        
6条回答
  •  甜味超标
    2020-12-05 21:44

    There is no way to enumerate members of the class in C++, since there is no reflection in C++. So you cannot have access to the variable name.

    You could use pointers to members though...

    void PrintMemberValue(int MyClass::*p, MyClass const & obj)
    {
        cout << "Member has value " << obj.*p;
    }
    
    MyClass obj;
    int MyClass::*p = &MyClass::a1;
    PrintMemberValue(p, obj);
    p = &MyClass::a2;
    PrintMemberValue(p, obj);
    etc
    

提交回复
热议问题