Boost logo

Boost :

From: itay_maman (itay_maman_at_[hidden])
Date: 2002-02-12 03:04:12


I'd like to offer (yet) another approach for the to_string() issue. I
think that an operator<< based inteface is the most natural way
for 'writing' values into strings. For example:

  std::string s;
  s = into_string<std::string>() << "current year: " << 2002 << ".\n";

This interface is consistent with the familiar output stream
interface, and (additionally) perfroms better than a chain of
string::operator+() calls.

The implentation of template function into_string() and additional
classes follows below.
[...And thanks a lot to Peter Dimov for his comments]

-Itay

 

template<class Tr = into_string_traits<string> >
class into_string_proxy
{
private:
   typedef into_string_proxy<Tr> self_type;

   Tr::stream_type m_out_stream;

public:
   
   ~into_string_proxy() { }
   into_string_proxy() {}

   into_string_proxy(const self_type& other)
      : m_out_stream(other.m_out_stream) {}

   template<typename T>
   self_type& operator<< (const T& x) {
      m_out_stream << x;

      return *this;
   }

   operator Tr::dst_type () {
      return m_out_stream.str();
   }
}; //into_string_proxy

template<class T> struct into_string_traits { };

struct into_string_traits<std::string>
{
   typedef std::string dst_type;
   typedef std::ostringstream stream_type;
};

template<class T>
into_string_proxy<into_string_traits<T> > into_string()
{
   return into_string_proxy<into_string_traits<T> >();
}

int main(int argc, char* argv[])
{
   int x = 4;
   int y = 6;
   std::string temp_s;

   temp_s = into_string<std::string>() << x << '*' << y << " = "
      << x*y << "!\n";

   std::cout << temp_s;
   return 0;
}

--- In boost_at_y..., "Peter Dimov" <pdimov_at_m...> wrote:
> I just wrote this:
>
> template<class V> std::string to_string(V const & v)
> {
> std::ostringstream os;
> os << v;
> return os.str();
> }
>
> template<> std::string to_string(std::string const & v)
> {
> return v;
> }
>
> for Nth time. Why don't we have this in Boost? And where should it
go?
>
> --
> Peter Dimov
> Multi Media Ltd.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk