Best way to take a snapshot of an object to a file - c++

What's the best way to output the public contents of an object to a human-readable file? I'm looking for a way to do this that would not require me to know of all the members of the class, but rather use the compiler to tell me what members exist, and what their names are. There have to be macros or something like that, right?
Contrived 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 output along the lines of "myCollection: stuff = value, otherStuff = value".
But then if another member is added to Container,
class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
string evenMoreStuff;
int otherStuff;
};
Container myCollection;
This time, the output of this snapshot would be "myCollection: stuff = value, evenMoreStuff=value, otherStuff = value"
Is there a macro that would help me accomplish this? Is this even possible? (Also, I can't modify the Container class.)
Another note: I'm most interested about a potential macros in VS, but other solutions are welcome too.

What you're 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

Boost has a serialization library that can serialize into text files. You will, however, not be able to get around with now knowing what members the class contains. You would need reflection, which C++ does not have.

Take a look at this library .

What you need is object serialization or object marshalling. A recurrent thema in stackoverflow.

I'd highly recommend taking a look at Google's Protocol Buffers.

There's unfortunately no macro that can do this for you. What you're looking for is a reflective type library. These can vary from fairly simple to home-rolled monstrosities that have no place in a work environment.
There's no real simple way of doing this, and though you may be tempted to simply dump the memory at an address like so:
char *buffer = new char[sizeof(Container)];
memcpy(buffer, containerInstance, sizeof(Container));
I'd really suggest against it unless all you have are simple types.
If you want something really simple but not complete, I'd suggest writing your own
printOn(ostream &) member method.

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

Related

Is there a way of seeing if user input matches variable name in c++? [duplicate]

This question already has answers here:
Convert string to variable name or variable type
(7 answers)
Closed 6 years ago.
If the title was not clear, I will try to clarify what I am asking:
Imagine I have a variable called counter, I know I can see its current value by doing something like:
std::cout << counter << std::endl;
However, assume I have lots of variables and I don't know which I'm going to want to look at until runtime.
Does anyone know a way I can fetch the value of a variable by using its name, for example:
std::cout << valueOf("counter") << std::endl;
I feel being able to do this might make debugging large complex projects easier.
Thanks in advance for your time.
Update: All the answers provided are valid and useful, however the main point is that reflection does not exist in C++ (and after reading the link recommended it is clear why).
As has been mentioned, you are looking for reflection in C++. It doesn't have that, and this answer explains why.
You can use an associative container as a std::map< std::string, your_variable_type > to link a string to a variable, assuming they are all of the same type.
If you have variable of different types, solution exists, as in boost::variant
No, not with C++ or its standard library. Of course, you can hack something up to emulate this behaviour. C++ allows you to choose methods at runtime, using polymorphism, so you can take advantage of that. In essence, you'll get the method to invoke at runtime, rather than the variable, and the method will return the vlaue:
struct Value {
virtual ~Value();
virtual std::string value() const = 0;
};
struct Counter : public Value {
int v;
std::string value() const {
istringstream ss(v);
return ss.str();
}
};
struct Mounter : public Value {
double v;
std::string value() const {
istringstream ss(v);
return ss.str();
}
};
Value* get_value();
// ...
cout << get_value()->value() << endl;
Alternatively, you can maintain a map keyed on strings, the names of the values, and then look up the values with their names.
C++ addresses all variables via address so there is no way of just saying valueOf a variable (Languages which allow this e.g. python, perl have a runtime keeping this information)
You can implement something allowing use of a name to find a value by storing the values and their names in a std::map.
Well if you really want to do something like this, you might try using std::map (map< string, int* > ). Hovewer this would restrict you to one variable type, unless you delve into some ugly pointer magic. Either way it will be ugly and trust me you really don't want to go down this path. Why do you even need such feature? If for debugging purposes, use a debugger.
As said already, C++ provides no reflection. But you can use some key/value mapping on your own.
When only one value type (e.g. int) is required, you can use an STL associative container (map) out of the box.
If you need to support multiple value types, i recommend a look into boosts Variant library.
This would need something akin to reflection or eval which C++ doesn't have.
No, C++ does not provide that facility. You may be able to hack something together with macros (or other trickery) but it's likely to be fairly ugly.
Since I can think of no good reason of the top of my head why this would be useful, perhaps you could enlighten us. When something cannot be done in a certain way, it's often good to step back to the base requirements and see if there's another way.

C++ Multi type map like PHP stdClass

I'm using the libjson for parsing a JSON file in C++. I was wondering if you could do something like a PHP style notation for a map:
Just some pseudo code:
mapObj["id"] = 4;
mapObj["tags"] = vector {"Foo", "Bar"};
structMapObj = {
{"name", "FooBar"},
{"size", 1234567},
{"date", "2014-12-24"}
};
mapObj["file"] = anotherMapObject;
// for the vector
mapObj["tags"][0];
mapObj["tags"][1];
mapObj["tags"].size();
mapObj["tags"].pushBack("Foo");
// for the map
mapObj["file"]["name"]
...
Is it possible to receive a result like this?
Maybe an enum for the current type in the BaseClass?
myObj["key"].getType; // returns a 1 for example an INT
I tried to make it with a BaseClass and a template class, but I wasn't able to iterate through the object. Or should I even overload the operators for my BaseClass? Or is it necessary to inherit the BaseClass for each case (a class for the map-type object, a class for the int-type, for string and so on)?
I'm a a little bit desperate right now. Just need someone who leads me into the right direction :-P
PS: I don't want to use boost :-/
Thank you very much,
Daniel
I appreciate that you don't want to use boost. However, this problem has been solved in boost.
You are essentially wanting a map of strings to variants.
Have a look at the source code for boost::variant and boost::any. Take particular note of how boost gets round the problem of recursive definitions, for example when you want to store a map inside an element of another map.
This will teach you more than you ever wanted to know on this subject :-)
There is an open source project for C++Builder programmer called JSonCBB library. This library provides a semantic like to your need: http://www.cbuilderblog.com/jsoncbuilderblog-class-library/

What is the best design pattern to register data "chunks"?

I have a library which can save/load on disk "chunks" which are POD structs with constant size and unique static CHUNK_ID field. So load looks somethink like this.
void Load(int docId, char* ptr, int type, size_t& size)...
If you want to add new chunk you just add struct with new CHUNK_ID and use Save Load functions to it.
What I want is to force all "chunks" to have functions like PrintHumanReadable, CompareThisTypeOfChunk etc(Ideally program should not compile without such functions). Also I want to mark/register/enumerate all chunk-structs.
I have a few ideas but all of them have problems.
Create base class with pure virtual functions PrintHumanReadable, CompareThisTypeOfChunk.
Problem:breaks pod type and requires library rewriting.
Implement factory which creates chunk struct from CHUNK_ID. Problem: compiles when I add new chunk without required functions.
Could you recomend elegant design solution for my problem?
Implement a simple code generator. You can use something like Mako or Cheetah (both Python libraries). Make a text file containing all the class names, then have the generator build the factory method and a series of methods which aren't really used but which refer to the desired methods in all the classes. This will also make it straightforward to enumerate the classes (again, using generated code).
The proper design pattern for this is called "use Boost.Serialization". It's really the best tool for writing objects to a format and then reading them back later. It can write in text, binary, and even XML formats (and others if you write a proper stream for them). It's can be non-intrusive, so you don't need to modify the objects to serialize them. And so forth.
Once you're using the proper tool for this job, you can then use whatever class hierarchy or other method you like to ensure that the proper functions for an object exist.
If you can't/won't use Boost.Serialization, then you're pretty much stuck with a runtime solution. And since the solution is runtime rather than compile time, there's no way to ensure at compile time that any particular chunk ID has the requisite functions.

Get list of available data member from a POD struct in C++

the question can sound a bit unusual. Let's take a POD struct:
struct MyStruct
{
int myInt;
double myDouble;
AnotherPOD* myPointer;
};
The compiler knows the list of available data members. Do you know any way to get list of data member name (and type) either at compile time (better) or at run time?
I have a huge amount of POD structs and I would like to automate the creation of operator<<.
I know I could create a parser for the header files, create some files and compile those. However, I am sure the compiler has already had this information and I would like to exploit it.
Any ideas?
Thanks
BOOST_FUSION_ADAPT_STRUCT introduces compile-time reflection (which is awesome).
It is up to you to map this to run-time reflection of course, and it won't be too easy, but it is possible in this direction, while it would not be in the reverse :)
I don't know of any way to do what you want directly, but you might want to take a look at clang, which is a compiler front-end implementation that you can make use of to do other things:
http://clang.llvm.org
I guess you'd then be able to traverse the abstract syntax tree it creates and get at the information you're after.
Well, standard C++ compilers can't do that, they lack reflection capabilities.
Sounds like a task for a code generator. So either use a toolkit to extract these informations from the headers or generate both headers and serialization functions from another source. Just make sure you do not repeat yourself.
I am afraid but C++ doesn't support reflection. You can use Boost.TypeTraits to achieve a restricted form of reflection at compile time.

I need some C++ guru's opinions on extending std::string

I've always wanted a bit more functionality in STL's string. Since subclassing STL types is a no no, mostly I've seen the recommended method of extension of these classes is just to write functions (not member functions) that take the type as the first argument.
I've never been thrilled with this solution. For one, it's not necessarily obvious where all such methods are in the code, for another, I just don't like the syntax. I want to use . when I call methods!
A while ago I came up with the following:
class StringBox
{
public:
StringBox( std::string& storage ) :
_storage( storage )
{
}
// Methods I wish std::string had...
void Format();
void Split();
double ToDouble();
void Join(); // etc...
private:
StringBox();
std::string& _storage;
};
Note that StringBox requires a reference to a std::string for construction... This puts some interesting limits on it's use (and I hope, means it doesn't contribute to the string class proliferation problem)... In my own code, I'm almost always just declaring it on the stack in a method, just to modify a std::string.
A use example might look like this:
string OperateOnString( float num, string a, string b )
{
string nameS;
StringBox name( nameS );
name.Format( "%f-%s-%s", num, a.c_str(), b.c_str() );
return nameS;
}
My question is: What do the C++ guru's of the StackOverflow community think of this method of STL extension?
I've never been thrilled with this solution. For one, it's not necessarily obvious where all such methods are in the code, for another, I just don't like the syntax. I want to use . when I call methods!
And I want to use $!---& when I call methods! Deal with it. If you're going to write C++ code, stick to C++ conventions. And a very important C++ convention is to prefer non-member functions when possible.
There is a reason C++ gurus recommend this:
It improves encapsulation, extensibility and reuse. (std::sort can work with all iterator pairs because it isn't a member of any single iterator or container class. And no matter how you extend std::string, you can not break it, as long as you stick to non-member functions. And even if you don't have access to, or aren't allowed to modify, the source code for a class, you can still extend it by defining nonmember functions)
Personally, I can't see the point in your code. Isn't this a lot simpler, more readable and shorter?
string OperateOnString( float num, string a, string b )
{
string nameS;
Format(nameS, "%f-%s-%s", num, a.c_str(), b.c_str() );
return nameS;
}
// or even better, if `Format` is made to return the string it creates, instead of taking it as a parameter
string OperateOnString( float num, string a, string b )
{
return Format("%f-%s-%s", num, a.c_str(), b.c_str() );
}
When in Rome, do as the Romans, as the saying goes. Especially when the Romans have good reasons to do as they do. And especially when your own way of doing it doesn't actually have a single advantage. It is more error-prone, confusing to people reading your code, non-idiomatic and it is just more lines of code to do the same thing.
As for your problem that it's hard to find the non-member functions that extend string, place them in a namespace if that's a concern. That's what they're for. Create a namespace StringUtil or something, and put them there.
As most of us "gurus" seem to favour the use of free functions, probably contained in a namespace, I think it safe to say that your solution will not be popular. I'm afraid I can't see one single advantage it has, and the fact that the class contains a reference is an invitation to that becoming a dangling reference.
I'll add a little something that hasn't already been posted. The Boost String Algorithms library has taken the free template function approach, and the string algorithms they provide are spectacularly re-usable for anything that looks like a string: std::string, char*, std::vector, iterator pairs... you name it! And they put them all neatly in the boost::algorithm namespace (I often use using namespace algo = boost::algorithm to make string manipulation code more terse).
So consider using free template functions for your string extensions, and look at Boost String Algorithms on how to make them "universal".
For safe printf-style formatting, check out Boost.Format. It can output to strings and streams.
I too wanted everything to be a member function, but I'm now starting to see the light. UML and doxygen are always pressuring me to put functions inside of classes, because I was brainwashed by the idea that C++ API == class hierarchy.
If the scope of the string isn't the same as the StringBox you can get segfaults:
StringBox foo() {
string s("abc");
return StringBox(s);
}
At least prevent object copying by declaring the assignment operator and copy ctor private:
class StringBox {
//...
private:
void operator=(const StringBox&);
StringBox(const StringBox&);
};
EDIT: regarding API, in order to prevent surprises I would make the StringBox own its copy of the string. I can think fo 2 ways to do this:
Copy the string to a member (not a reference), get the result later - also as a copy
Access your string through a reference-counting smart pointer like std::tr1::shared_ptr or boost:shared_ptr, to prevent extra copying
The problem with loose functions is that they're loose functions.
I would bet money that most of you have created a function that was already provided by the STL because you simply didn't know the STL function existed, or that it could do what you were trying to accomplish.
It's a fairly punishing design, especially for new users. (The STL gets new additions too, further adding to the problem.)
Google: C++ to string
How many results mention: std::to_string
I'm just as likely to find some ancient C method, or some homemade version, as I am to find the STL version of any given function.
I much prefer member methods because you don't have to struggle to find them, and you don't need to worry about finding old deprecated versions, etc,. (ie, string.SomeMethod, is pretty much guaranteed to be the method you should be using, and it gives you something concrete to Google for.)
C# style extension methods would be a good solution.
They're loose functions.
They show up as member functions via intellisense.
This should allow everyone to do exactly what they want.
It seems like it could be accomplished in the IDE itself, rather than requiring any language changes.
Basically, if the interpreter hits some call to a member that doesn't exist, it can check headers for matching loose functions, and dynamically fix it up before passing it on to the compiler.
Something similar could be done when it's loading up the intellisense data.
I have no idea how this could be worked for existing functions, no massive change like this should be taken lightly, but, for new functions using a new syntax, it shouldn't be a problem.
namespace StringExt
{
std::string MyFunc(this std::string source);
}
That can be used by itself, or as a member of std::string, and the IDE can handle all the grunt work.
Of course, this still leaves the problem of methods being spread out over various headers, which could be solved in various ways.
Some sort of extension header: string_ext which could include common methods.
Hmm....
That's a tougher issue to solve without causing issues...
If you want to extend the methods available to act on string, I would extend it by creating a class that has static methods that take the standard string as a parameter.
That way, people are free to use your utilities, but don't need to change the signatures of their functions to take a new class.
This breaks the object-oriented model a little, but makes the code much more robust - i.e. if you change your string class, then it doesn't have as much impact on other code.
Follow the recommended guidelines, they are there for a reason :)
The best way is to use templated free functions. The next best is private inheritance struct extended_str : private string, which happens to get easier in C++0x by the way as you can using constructors. Private inheritance is too much trouble and too risky just to add some algorithms. What you are doing is too risky for anything.
You've just introduced a nontrivial data structure to accomplish a change in code punctuation. You have to manually create and destroy a Box for each string, and you still need to distinguish your methods from the native ones. You will quickly get tired of this convention.