The behavior of your code is not specified according to the C ++ standard.
Description
Next (I removed std::endl for simplicity)
std::cout << "Hello, world!" << print( std::cout );
equivalent to this:
std::operator(operator<<(std::cout, "Hello, World!"), print(std::cout));
which is a function call, passing two arguments:
- First argument:
operator<<(std::cout, "Hello, World!") - Second argument:
print(std::cout)
Now the standard does not specify the order in which arguments are evaluated. It is not specified. But your compiler seems to evaluate the second argument first, so it prints "How are you?" first evaluating the second argument to a value of type std::ostream& , which is then passed to the call shown above (this value is the std::cout object itself).
Why is hexadecimal output?
You get hexadecimal output because the second argument evaluates to std::cout , which prints as a hexadecimal number, because std::cout implicitly converted to a pointer value of type void* , so it prints as a hexadecimal number.
Try the following:
void const *pointer = std::cout; //implicitly converts into pointer type! std::cout << std::cout << std::endl; std::cout << pointer << std::endl;
It will print the same value for both. For example, this example in ideone prints this:
0x804a044 0x804a044
Also note that I did not use explicit casts; rather, std::cout implicitly converted to a pointer type.
Hope this helps.
What is the correct way to write a function that inserts data into a stream, but can also be associated with the <
When does it depend on what you mean by chain? Obviously, the following will not work (as described above):
std::cout << X << print(std::cout) << Y << Z; //unspecified behaviour!
No matter how you write print() .
However, this is clearly defined:
print(std::cout) << X << Y << Z; //well-defined behaviour!