1

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 right way to do it?

rmflow
  • 4,445
  • 4
  • 27
  • 41

1 Answers1

3

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.

Jason
  • 31,834
  • 7
  • 59
  • 78
  • So, what exactly are you supposed to do if you have operator<< overloaded with `std::ostream`s for some other purpose with this object? Like if the format you store in the `property_tree` should look different than what you use to print it for display purposes? – Nicol Bolas Sep 28 '11 at 07:08
  • @NicolBolas: Was there another option that I'm missing? I don't see a way that you can overload `operator<<` twice for std::ostream, one for the specific instance in the `boost::property_tree`, and another for `std::cout`, etc. The only thing I could think of is to either investigate if there is some type of derived class that `boost::property_tree` is using for I/O that you can use to create a more specific overload of `operator<<`. Otherwise you could possibly wrap `std::cout` in another class, and overload `operator<<` for your `Foo` class and the `std::cout` wrapper. Any other options? – Jason Sep 28 '11 at 17:41