Question

cout is object of class ostream, and ostream is typedef of basic_ostream:

extern ostream cout;

typedef basic_ostream<char> ostream;

template <class charT, class traits = char_traits<charT> >
  class basic_ostream;

but none of these classes has operator<

So I can't understand why this code compiles without any errors:

std::cout < "aaa";
Was it helpful?

Solution

In C++ language operator < makes the compiler to consider a built-in candidate function of the form

bool operator<(T, T);

for every possible pointer type T. In particular, that means that there's such a function for void * type. This is the function that is applicable in your case. String literal is implicitly convertible to void * and std::cout is also implicitly convertible to void *.

You can reproduce the same behavior with the following minimalist example

struct X {
  operator void *() { return 0; }
};

int main() {
  X() < "";
}

The above would apply to C++03. I'm not sure why it compiles in C+11 tough (assuming it does), since in C++11 stream conversion to void * was replaced with explicit conversion to bool.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top