开发者

What is the right way to put objects to boost::property_tree?

Consider following example:

#include <boost\property_tree\ptree.hpp>
#include <boost/any.hpp>

typedef boost::property_tree::ptree PT;

struct Foo
{
    int bar;
    int egg;
    Foo(): bar(), egg() {}
};


int main()
{
    Foo foo;
    foo.bar = 5;
    PT pt;
    pt.put<Foo>("foo", foo);
    return 0;
}

I'm new to boost and I'm willing to put a Foo object into property tree. The example above will not compile giving an error:

c:\mingw\bin\../lib/gcc/mingw32/4.5.2/../../../../include/boost/property_tree/stream_translator.hpp:33:13: error: no match for 'operator<<' in 's << e'

Can anyone suggest the r开发者_运维问答ight way to do it?


Simply create an overloaded operator<< for your Foo object-type. This can be done by creating a function that takes the members of your Foo object-type, and passes them via the operator<< to a ostream object-type. Here is a very simple example:

ostream& operator<<(ostream& out, Foo output_object)
{
    out << egg << " " << bar;
    return out;
}

This works because the int types you are using as the members of your Foo object-type are calling the overloaded version of operator<< for ostream and int. So if the objects that are part of your Foo type are not already overloaded, then you would also have to create overloaded operator<< functions for those types as well.

Once this is done, your code can be called anywhere like so:

Foo test;
cout << test; //will print out whatever the values of "egg" and "bar" are

Additionally, any other code that attemps to use operator<< with an ostream object and your Foo type as operands will function correctly as well.

Finally, you can either inline the overloaded function and place it in a header-file, or you can create the function declaration in a header, and then define the function in a code module somewhere else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜