Boost logo

Boost Users :

From: Olaf Peter (ope-devel_at_[hidden])
Date: 2008-03-29 15:56:43


Hello,

for formatting output I wrote the following classes:

---8<---
namespace /* anonymous */ {

     namespace mpl = ::boost::mpl;
     using ::boost::enable_if;
     using ::boost::xpressive::sregex;
     using ::boost::xpressive::as_xpr;

     template<typename StringT>
     struct is_string : mpl::false_ { };

     template<>
     struct is_string<std::string> : mpl::true_ { };

     template <typename Tp, typename Enable = void>
     struct formatter
     {
         formatter( const Tp& data )
             : output( data )
         { }

         std::ostream& write_on( std::ostream& os ) const
         {
             os << output;
             return os;
         }

     private:
         const Tp& output;
     };

     template <typename Tp>
     struct formatter<Tp, typename enable_if< is_string<Tp> >::type>
     {
         formatter( const Tp& data )
             : output( data ),
               re( as_xpr("\r") ),
               format("\n")
         { }

         std::ostream& write_on( std::ostream& os ) const
         {
             using ::boost::xpressive::regex_replace;

             std::ostream_iterator<std::ostream::char_type> out_iter( os );
             regex_replace( out_iter, output.begin(), output.end(), re,
format );
             return os;
         }

     private:
         const Tp& output;
         const sregex re;
         const std::string format;
     };

}
--->8---

Mainly, this replaces all '\r' by '\n' in all string in the given data,
e.g.:

---8<---
template<typename DataT>
void foo::write_key_data_pair( std::ostream& os,
     const std::string& key, const DataT& data ) const
{
     os << "[" << key << "]"
        << " "
         ;
     formatter<DataT>( data ).write_on( os );
     os << std::endl
         ;

}
--->8---

Anyway, overloading global operator<<() as

template<typename T>
static inline
std::ostream& operator<<( std::ostream& os, const T& rhs )
{
     return rhs.write_on( os );
}

would force all to have a write_on member function, isn't it. Is there a
way around and even use operator<<() notation ??

Thanks,
Olaf


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