The << operator cannot output std :: endl - Fix?

The following code gives an error when it should only output std::endl :

 #include <iostream> #include <sstream> struct MyStream { std::ostream* out_; MyStream(std::ostream* out) : out_(out) {} std::ostream& operator<<(const std::string& s) { (*out_) << s; return *out_; } }; template<class OutputStream> struct Foo { OutputStream* out_; Foo(OutputStream* out) : out_(out) {} void test() { (*out_) << "OK" << std::endl; (*out_) << std::endl; // ERROR } }; int main(int argc, char** argv){ MyStream out(&std::cout); Foo<MyStream> foo(&out); foo.test(); return EXIT_SUCCESS; } 

Error:

 stream1.cpp:19: error: no match for 'operator<<' in '*((Foo<MyStream>*)this)->Foo<MyStream>::out_ << std::endl' stream1.cpp:7: note: candidates are: std::ostream& MyStream::operator<<(const std::string&) 

Thus, it can output a string (see the line above for errors), but not only std::endl , apparently because std::endl not a string, but the definition of operator<< asks for a string.

Failed operator <<:

  template<class T> std::ostream& operator<<(const T& s) { ... } 

How can I make the code work? Thank you

+4
source share
1 answer

You need to add this to your struct MyStream :

  std::ostream& operator<<( std::ostream& (*f)(std::ostream&) ) { return f(*out_); } 

std::endl is a function that adds a new line and clears the underlying stream; this function signature takes this function and applies it to the ostream element.

Then, as a test, defining foo::test as

  void test() { (*out_) << "start"; (*out_) << std::endl; (*out_) << "done"; } 

will output correctly

  start
 done
+8
source

Source: https://habr.com/ru/post/1306537/


All Articles