Boost logo

Boost Users :

From: Christian Henning (chhenning_at_[hidden])
Date: 2007-05-21 10:04:07


The following solution doesn't use boost::lambda anymore. Also the
Base class is abstract again. So, I think this solution is better:

#include <string>
#include <sstream>
#include <boost/cstdint.hpp>
#include <vector>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <iostream>

class Base {
public:

   virtual std::string to_String ( boost::uint32_t indent ) = 0;

};

class A : public Base {
public:

   A ( boost::uint32_t value )
       : m_value ( value )
   {}

   virtual std::string to_String ( boost::uint32_t indent )
   {
      std::stringstream output;
      output << std::string(indent, ' ') << m_value;
      return output.str();
   }

private:

   boost::uint32_t m_value;
};

class D : public Base {
public:

   D ( boost::uint32_t value )
       : m_value ( value )
   {}

   virtual std::string to_String ( boost::uint32_t indent )
   {
       std::stringstream output;

       for ( boost::uint32_t i = 0; i < indent; i++ )
           {
               output << " ";
           }

       output << m_value;

       return output.str();
   }

private:

   boost::uint32_t m_value;
};

int main ( int, char** )
{
   typedef boost::shared_ptr<A> A_ptr_t;
   typedef boost::shared_ptr<D> D_ptr_t;

   typedef std::vector < boost::shared_ptr<Base> > Data_t;
   Data_t m_data;

   A_ptr_t a ( new A ( 50 ) );
   D_ptr_t d ( new D ( 30 ) );

   m_data.push_back ( a );
   m_data.push_back ( d );

   boost::uint32_t indent_value = 4;

   std::transform( m_data.begin()
                 , m_data.end()
                 , std::ostream_iterator<std::string>( std::cout, "" )
                 , boost::bind( &Base::to_String
                              , _1
                              , indent_value ));

   return 0;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net