Re: operator << for ostringstream returning ostream is unintuitive
On 17 Nov., 21:46, Patrik Kahari <patrik.kah...@googlemail.com> wrote:
Is it not a reasonable user assumtion that the return type of <<
should be the same the type as its first argument? (So that any
operation that is valid for the first argument should also be valid
for the return type, to allow intuitive chaining)
However, for ostringstream the return type of operator << is the base
type ostream rather than ostringstream itself (because ostringstream
does not provide any << overload of its own).
Same is valid for std::basic_fstream. And shouldn't we distinguish
also for std::basic_stringstream and basic_ostringstream as well?
As a ostringstream user
I find this to be inconvenient and bit surprising. Am I being
unreasonable?
#include <sstream>
void libFunc(std::ostringstream& msg);
int main(void) {
libFunc( std::ostringstream() << "Test" << 1); // Error
(std::ostringstream() << "Test" << 2).str(); //Error
I think this last line clearly proves as show stopper
for your proposal. Thinking consequently, users
cannot stop by writing
template<typename charT, typename traits, typename X>
std::basic_ostream<charT,traits>& operator<<
(std::basic_ostream<charT,traits>&, const X&);
but instead they need to add even more overloads like:
template<typename charT, typename traits, typename Alloc, typename X>
std::basic_ostringstream<charT,traits, Alloc>& operator<<
(std::basic_ostringstream<charT,traits, Alloc>&, const X&);
template<typename charT, typename traits, typename X>
std::basic_ofstream<charT,traits>& operator<<
(std::basic_ofstream<charT,traits>&, const X&);
Where will that end?
//need to be more verbose to get it to work.
std::ostringstream namedsstr1;
namedsstr1 << "Test" << 1;
libFunc( namedsstr1 ); // OK
std::ostringstream namedsstr2;
namedsstr1 << "Test" << 2;
namedsstr2.str(); //OK
}
IMO the disadvantages of your proposal outweigh it's advantages.
Just my 2 Euro cents,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]