Listing F
#include <string>
#include <sstream>
#include <iostream>
 
 
struct str_stream
{
    std::stringstream & underlying_stream() const
    { return m_streamOut; }
 
 
    operator std::string() const
    {
        std::cout << "conversion operator called" << std::endl;
       return m_streamOut.str();
    }
private:
    mutable std::stringstream m_streamOut;
};
 
 
// ... helper - allow explicit conversion to string
class as_string {};
inline std::ostream & operator<< ( std::ostream & streamOut, const as_string &)
{
    std::cout << "explicit conversion operator called" << std::endl;
    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;
        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) ;
}
 
 
 
 
int main()
{
    int nWordsCount;
    // ... calculate words count
    nWordsCount = 48;
 
 
    std::cout << "building str: implicit conversion should be applied" << std::endl;
 
 
    // implicit conversion to string
    std::string str = str_stream() << "We have " << nWordsCount << " words";
 
 
    std::cout << "building str2: EXPLICIT conversion should be applied" << std::endl;
 
 
    // explicit conversion to string
    std::string str2 =
        str_stream() << "We have " << nWordsCount << " words" << as_string();
  
    std::cin.get();
    return 0;
}