The best way to take a snapshot of a subject to a file
What is the best way to output the public content of an object to a human readable file? I'm looking for a way to do this that doesn't require me to know all the members of a class, but rather use a compiler to tell me what the members are and what their names are. There must be macros or something like that, right?
Simplified example:
class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
int otherStuff;
};
Container myCollection;
I would like to be able to do something to see the output along the lines "myCollection: stuff = value, otherStuff = value". But if another member is added to the container,
class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
string evenMoreStuff;
int otherStuff;
};
Container myCollection;
This time, the output of this snapshot will be "myCollection: stuff = value, evenMoreStuff = value, otherStuff = value"
Is there a macro that can help me accomplish this? Is it possible? (Also, I can't change the Container class.) Another note: I'm most interested in potential macros in VS, but other solutions are also welcome.
source to share
What you are looking for is "[reflection] ( http://en.wikipedia.org/wiki/Reflection_(computer_science)#C.2B.2B) ".
I found two promising links with a google search for "C ++ reflection":
source to share
You need serialization of objects or sorting of objects. A recurrent thema on stackoverflow.
source to share
Unfortunately, there is no macro that can do this for you. What you are looking for is a reflective type library. They can range from fairly simple to homemade twisted monsters that don't have a place in a work environment.
There is no real easy way to do this, and while you might be tempted to just flush memory at an address like this:
char *buffer = new char[sizeof(Container)];
memcpy(buffer, containerInstance, sizeof(Container));
I would really suggest against it, unless you have simple types.
If you want something really simple but incomplete, I would suggest writing your own
printOn(ostream &)
member method.
source to share