The default copy constructor that is synthesized by the compiler for
a class that does not define its own does the right thing: it copies
all the members from one object to another.
I want to do something similar. I want to write a method
template <typename T>
T f(const T& obj) {
// for each member var i of obj, I want to call some method g(obj.i)
}
Now I don’t know what the names of the member variables are. If this was
the copy constructor, I could call the assignment operator instead of g.
Clearly the compiler does this (but maybe it does this after it has inferred
the name of the members of the class). Is it even possible to do this
for any class T ?
The compiler has some internal data structure representing each class. When it comes to synthesize the copy constructor, it can refer to this structure in order to figure out what code it needs to emit (how many copies, how each one is done, and what the addresses of the members are in relation to the source and destination object addresses).
As a mere C++ programmer, you don’t have access to this internal compile-time data structure, so you’re pretty much out of luck. You basically have to list the members and hope you don’t leave any out.
You could perhaps do work with the preprocessor (or if not the preprocessor then a preprocessor), to annotate your struct definition with extra information that you can use to generate the list of one call for each member.