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.

+1


source to share


7 replies


Have a look at this library .



+1


source


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":



http://www.garret.ru/cppreflection/docs/reflect.html

http://seal-reflex.web.cern.ch/seal-reflex/index.html

+2


source


Boost has a serialization library that can be serialized to text files. However, you cannot get by with knowing what class members are contained. You will need reflection, which C ++ does not have.

+2


source


You need serialization of objects or sorting of objects. A recurrent thema on stackoverflow.

+1


source


I highly recommend taking a look at Google Protocol Buffers .

+1


source


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.

0


source


XDR is one way to do this in a platform independent way.

0


source







All Articles