Reputation: 2711
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 ?
Upvotes: 0
Views: 1484
Reputation: 9691
No, you can't do this. C++ doesn't have method reflection, though you can do this by working within a framework like Qt. (Which btw is a great framework, I use it all the time and it provides only a paper-thin layer on top of C++.) The compiler doesn't need to do this either--that is, it doesn't need to infer names of members. It just knows the memory offset from the address of the object and the type of each member, and copies those to the target object by calling their constructors.
Upvotes: 0
Reputation: 279225
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.
Upvotes: 5