When I ran the following program
#include <iostream>
int main()
{
char c = 'a';
std::cout << c << std::endl;
std::cout.operator<<(c) << std::endl;
return 0;
}
I got the output
a
97
Digging further at http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt, I noticed that std::ostream::operator<<()
does not have an overload that has char
as the argument type. The function call std::cout.operator<<(a)
gets resolved to std::ostream::operator<<(int)
, which explains the output.
I am assuming that the operator<<
function between std::ostream
and char
is declared elsewhere as:
std::ostream& operator<<(std::ostream& out, char c);
Otherwise, std::cout << a
would resolve to std::ostream::operator<<(int)
.
My question is why is that declared/defined as a non-member function? Are there any known issues that prevent it from being a member function?
widen
. – Agiooperator<<
taking acharT
and anoperator<<
taking achar
. That's going to be tricky to do as members sincecharT
can - and often is -char
. – Pronationtemplate<class traits> basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& out, char c);
for this case – Agiochar
-inserters orchar*
-inserters, in various flavours. – Agio