David Lee wrote:
[color=blue]
> Hi, all
> I got the following code from
>
http://builder.com.com/5100-6370_14-5079969.html,
> but it can't compile, neither can I figure out how to fix it. Anyone
> pls give me an
> explanation?
>
> 1 #include <string>
> 2 #include <sstream>
> 3 #include <iostream>
> 4
> 5 class str_stream
> 6 {
> 7 public:
> 8 std::stringstream & underlying_stream() const
> 9 { return m_streamOut; }
> 10
> 11 operator std::string() const
> 12 {
> 13 return m_streamOut.str();
> 14 }
> 15
> 16 private:
> 17 mutable std::stringstream m_streamOut;
> 18 };
> 19
> 20 template<class T>
> 21 const str_stream & operator<< (const str_stream & out, const T
> & value)
> 22 {
> 23 out.underlying_stream() << value;
> 24 return out;
> 25 }
> 26
> 27 int main()
> 28 {
> 29 int num = 48;
> 30 std::string str;
> 31
> 32 // str_stream s;
> 33 // str = s << "We have " << num << " words";
> 34 str = str_stream() << "We have " << num << " words";[/color]
In this line, you bind the temporary str_stream() to the non-const reference
parameter of operator<<( str_stream &, T const & ). This does not fly
because the standard forbids that.
[color=blue]
> 35
> 36 std::cout << str << std::endl;
> 37
> 38 return 0;
> 39 }
> 40
>[/color]
Here is a fix:
#include <string>
#include <sstream>
#include <iostream>
class str_stream
{
public:
std::stringstream & underlying_stream() const
{ return m_streamOut; }
operator std::string() const
{
return m_streamOut.str();
}
str_stream & me ( void ) {
return ( *this );
}
private:
mutable std::stringstream m_streamOut;
};
template<class T>
const str_stream & operator<< (const str_stream & out, const T & value)
{
out.underlying_stream() << value;
return out;
}
int main() {
int num = 48;
std::string str;
str = str_stream().me() << "We have " << num << " words";
std::cout << str << std::endl;
return 0;
}
This compiles because it is legal to call a non-const member function of a
temporary object. The return value of me() is a reference, which can be
bound to the first parameter of operator<<(). That the reference just so
happens to refer to a temporary is immaterial.
Best
Kai-Uwe Bux