Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

c++ - Find the list of member variables of a class and their types?

I haven't ever heard it's possible, but asking with the hope that it might.
For a class with many more member variables than this:

class A
{
 public:
  SomeOtherClass* s;
  int i;
  int j;
  A() {}
  A(const A& soc): s(soc.s->Clone()), i(soc.i), j(soc.j) {}
};

I always have to remember that if I add another variable int k to the class, I'll also have to add it in the initialization list k(soc.k) and sometimes in the destructor too. I've had to add/remove member variables so many times and it's really annoying to forget about the copying in the initialization list and finding the omission much much later while debugging.

Therefore, I wanted to know if there's a syntax/logic through which I can find out the list of member variables of a class and their types, so that I can maybe iterate through them and decide which of them need to be copied in the copy ctor and which of them need to be deep copied?

I don't see why the creators of C++ couldn't have included such a facility, since except for virtual members, the memory locations of variables would be contiguous and their types are known too. Even if they were extern or virtual, the type and size would be known at runtime. So shouldn't it be possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no reflection in C++, so you'll need an external library to do this. The creators of C++ didn't implement this feature because it implies a performance penalty, and performance is one of C++'s main goals.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...