Re: Dummy streams: eating std::endl?
lindahlb@hotmail.com writes:
#include <iostream>
std::endl is declared in the header <ostream>, which is not
necessarily pulled in by <iostream>.
using namespace std;
struct Ignore_Stream
{
#if 1
template<typename T>
Ignore_Stream operator<<(T) const;
#else
template<typename Char, typename Traits>
Ignore_Stream operator<<(basic_ostream<Char,Traits> &
(*)(basic_ostream<Char,Traits> &)) const;
#endif
};
int main(int argc, char * argv[])
{
Ignore_Stream() << endl;
return 0;
}
For both definitions, g++ complains about the above:
error: no match for 'operator<<' in 'Ignore_Stream() << std::endl'
Why? Is this a non-conformance problem, or is this behavior expected?
And how can I get the above to eat std::endl?
The problem is that std::endl is a function template, with two
typename parameters like the second version of the operator<< member
template in your code above.
When we write
std::cout << std::endl;
, std::endl is specialized so as to fit the appropriate overload of
operator<< for std::cout, i.e. for Char==char and
Traits==std::char_traits<char>.
When you write
Ignore_Stream() << endl;
, however, the compiler doesn't know which character type you want
std::endl and operator<< to be specialized for.
If Ignore_Stream commits itself to a character type, e.g.:
struct Ignore_Stream
{
Ignore_Stream
operator<<(std::basic_ostream<char,std::char_traits<char> > &
(*)(std::basic_ostream<char,std::char_traits<char> > &));
};
, the statement
Ignore_Stream() << endl;
will be accepted.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]