You cannot fix this function. Nothing in the specification requires a compiler to evaluate a function call in an expression in any particular order relative to some unrelated statement in the same expression. Thus, without changing the call code, you cannot evaluate MyPrint() after std::cout << "Value: "
The order from left to right is set for expressions consisting of several consecutive <operators, so this will work. Operator point <Flow return is that when the operators are bound, each of them is provided with an LHS by evaluating the operator to its left.
You cannot achieve the same with free function calls, because they do not have LHS. MyPrint() returns an object equal to std::cout , as well as std::cout << "Value: " , so you effectively do std::cout << std::cout , which prints this hex value.
Since the desired result:
Value: 12
the βrightβ thing is to really override the operator <This often means you need to either make it a friend or do it:
class WhateverItIsYouReallyWantToPrint { public: void print(ostream &out) const {
If overriding operator<< for your class is not suitable, for example, because there are several formats that you want to print, and you want to write different functions for each of them, then you should either abandon the idea of ββa chain of operators and just call the function, or write several classes that take your object as a constructor parameter, each with different operator overloads.
Steve jessop
source share