Re: A std::ostringstream wrapper for on-the-fly streaming - is this
dodgy?
On Aug 3, 3:29 pm, Stuart Golodetz
<sgolod...@NdOiSaPlA.pMiPpLeExA.ScEom> wrote:
Just wondering if anyone can see a problem with the code
below? The intent is to allow you to construct strings
"on-the-fly" via streaming, e.g. f(OSSWrapper() << "Wibble "
<< 42). The code works, but I'm concerned that it might not be
the best practice in the world - particularly the need to use
a const reference to bind to the temporary, and the ensuing
need to make m_os mutable. Seems a bit icky to me! Is there a
better way?
#include <iostream>
#include <sstream>
#include <string>
class OSSWrapper
{
private:
mutable std::ostringstream m_os;
public:
operator std::string() const
{
return m_os.str();
}
template <typename T>
friend const OSSWrapper& operator<<(const OSSWrapper& ossw, const=
T& rhs)
{
ossw.m_os << rhs;
return ossw;
}
Instead of using a template friend, why not a template member
function here. Member functions (even non-const) can be called
on temporary objects.
More generally, you'll have trouble with this (member or not)
when passing arrays (string literals) and function templates
(like std::endl or other manipulators), the first because the
array to pointer conversion doesn't apply when matching a
reference (It should apply within the function, but I've had
problems with some compilers about this), and the second because
the presense of two templates makes type deduction pretty much
impossible. This can be solved by overloads:
OSSWrapper& operator<<( T const& obj )
{
m_os << rhs ;
return *this ;
}
OSSWrapper& operator<<( char const* cString )
{
m_os << cString ;
return *this ;
}
OSSWrapper& operator<<( std::ostream& (*manip)( std::ostream& ) )
{
m_os << cString ;
return *this ;
}
OSSWrapper& operator<<( std::ios& (*manip)( std::ios& ) )
{
m_os << cString ;
return *this ;
}
};
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34