Listing H
#include <string>
#include <sstream>
#include <iostream>
 
 
struct str_stream
{
    std::stringstream & underlying_stream() const
    { return m_streamOut; }
 
 
    operator std::string() const
    {
        return m_streamOut.str();
    }
private:
   mutable std::stringstream m_streamOut;
 
 
#ifndef NDEBUG
public:
    void recalculate_string() const
    { m_string = m_streamOut.str(); }
private:
    mutable std::string m_string;
#endif
};
 
 
// ... helper - allow explicit conversion to string
class as_string {};
inline std::ostream & operator<< ( std::ostream & streamOut, const as_string &)
{
    return streamOut;
}
 
 
 
 
 
 
namespace Private
{
    // what should we return when calling write_to_stream ???
    template< class type>
    struct return_from_write_to_stream
    {
        typedef const str_stream & return_type;
    };
 
 
    template<>
        struct return_from_write_to_stream< as_string>
    {
        typedef std::string return_type;
    };
 
 
 
 
    template< class type>
        inline typename return_from_write_to_stream< type>::return_type
            write_to_stream ( const str_stream & out, const type & value)
    {
        out.underlying_stream() << value;
#ifndef NDEBUG
        out.recalculate_string();
#endif
        return out;
    }
 
 
}
 
 
 
 
template< class type>
inline typename Private::return_from_write_to_stream< type>::return_type operator<< ( const str_stream & out, const type & value)
{
    return Private::write_to_stream( out, value) ;
}
 
 
 
 
#include <iomanip>
 
 
int main()
{
    std::string s = str_stream() << std::setfill( '0') << std::setw( 4) << 35;
    std::cout << s;
    std::cin.get();
    return 0;
}