C++ Composite ostream Output

Composite ostream Output
This example uses the Printable interface as explained in the C++ ostream Output article. using namespace std; using namespace boost;
 * 1) include
 * 2) include
 * 3) include 
 * 4) include 

// 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 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