c++ - Why is operator<< function between std::ostream and char a non-member function? -
when ran following program
#include <iostream> int main() { char c = 'a'; std::cout << c << std::endl; std::cout.operator<<(c) << std::endl; return 0; }
i got output
a 97
digging further @ http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt, noticed std::ostream::operator<<()
not have overload has char
argument type. function call std::cout.operator<<(a)
gets resolved std::ostream::operator<<(int)
, explains output.
i assuming operator<<
function between std::ostream
, char
declared elsewhere as:
std::ostream& operator<<(std::ostream& out, char c);
otherwise, std::cout << a
resolve std::ostream::operator<<(int)
.
my question why declared/defined non-member function? there known issues prevent being member function?
the set of inserters std::basic_ostream
includes partial specializations inserting char
, signed char
, unsigned char
, such basic_ostream<char, ...>
streams. note these specializations made available basic_ostream<char, ...>
streams only, not basic_ostream<wchar_t, ...>
streams or streams based on other character type.
if move these freestanding templates main basic_ostream
definition, become available specializations forms of basic_ostream
. apparently, library authors wanted prevent happening.
i don't know why wanted introduce these specializations on top of more generic
template<class chart, class traits> basic_ostream<chart,traits>& operator<<(basic_ostream<chart,traits>&, char);
inserter, apparently had reasons (optimization?).
the same situation exists c-string inserters. in addition more generic inserter
template<class chart, class traits> basic_ostream<chart,traits>& operator<<(basic_ostream<chart,traits>&, const char*);
the library specification declares more specific
template<class traits> basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>&, const char*);
and on.
Comments
Post a Comment