c++compiler-errorsoperator-overloadingostreamostringstream

binary '<<' : no operator found which takes a left-hand operand of type 'std::basic_ostream<char, std::char_traits<char>>'


There is a function which gets std::ostream& as an arguments and performs some operations:

inline std::ostream& my_function(std::ostream& os, int n) {
      // some operations
      return os;    
}

And there is another function that calls my_function:

void caller_function(int  n) {
    std::ostringstream ostsr;
    ostsr << my_function(ostsr, n);
}

The visual studio 2015 compiler reports an error:

error C2679: binary '<<' : no operator found which takes a left-hand operand of type 'std::basic_ostream<char, std::char_traits<char>>' 

std::ostringstreamm has an inherited and overloaded operator<< which takes manipulator function for this case tha manipulator function is my_function The overloaded operator<<:

ostream& operator<< (ostream& (*pf)(ostream&));

So what is the issue and how to fix it?


Solution

  • Your function does not match ostream& (*pf)(ostream&) but ostream& (*pf)(ostream&, int). You would have to bind the second argument somehow. Using lambdas for that purpose will be difficult though because if you capture (and use) anything, such as n in your case, the lambda can no longer decay to a function pointer as it otherwise could.

    I don't see a reentrant way you could use the manipulator overload with runtime parameters like n, as anything matching ostream& (*pf)(ostream&) cannot have state (or at best rely on some global, which is ugly and unsafe) and has no way of getting that additional information through parameters either.

    (As n.m. pointed out in the comments, you are also not passing the function to << but its return value, which is not what you intended).