From Schmid.wiki
Jump to: navigation, search

Composite ostream Output

This example uses the Printable interface as explained in the C++ ostream Output article.

#include <iostream>
#include <sstream>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/foreach.hpp>
using namespace std;
using namespace boost;

// Implements a simple version of the Composite design pattern.
class Component : public Printable {
public:
    virtual void print(ostream & out) const { out << "Component"; }
};

class Composite : public Component {
public:
    // Indented tree output
    virtual void print(ostream & out) const {
        static int indentation = -1;
        indentation++;

        // Compute indentation string
        ostringstream indentation_text;
        for(int i = 0; i < indentation; i++) indentation_text << "   ";

        out << "Composite with:\n";

        // Output children
        BOOST_FOREACH(const Component & c, children_)
            out << indentation_text.str() << "+- " << c << "\n";

        indentation--;
    }
    void adopt(Component * c) { children_.push_back(c); }
private:
    ptr_list<Component> children_;
};

int main() {
    // build small tree
    Composite root;
    root.adopt(new Component);
    Composite * c = new Composite;
    c->adopt(new Component);
    root.adopt(c);

    cout << root << endl;
}

Example output:

Composite with:
+- Component
+- Composite with:
   +- Component

References