Operator Overloading and Handling std::endl in Custom Stream Implementations
Consider the following code snippet where operator<< is overloaded:
template <typename T> UIStream& operator<< (const T); UIStream my_stream; my_stream << 10 << " heads";
While this works as expected, attempting to use my_stream << endl results in a compilation error stating "binary '<<' : no operator found which takes a left-hand operand of type 'UIStream'..."
To resolve this issue, it's important to understand that std::endl is not an object but a function. In std::cout, it's utilized by implementing operator<< to accept a function pointer with the same signature as std::endl. When called, the function is invoked and its return value is forwarded.
A custom implementation of the operator<< can be defined to handle std::endl in a similar manner:
struct MyStream { templateMyStream& operator<< (const T& x) { std::cout << x; return *this; } // Function that takes a custom stream and returns it typedef MyStream& (*MyStreamManipulator)(MyStream&); // Accept function with custom signature MyStream& operator<< (MyStreamManipulator manip) { return manip(*this); } // Define a custom endl for this stream (matches MyStreamManipulator signature) static MyStream& endl(MyStream& stream) { std::cout << std::endl; stream << "Called MyStream::endl!" << std::endl; return stream; } }; This custom implementation defines an operator<< that accepts two types:
- The first type is a generic function pointer that takes a reference to the MyStream object and returns a reference to the same object.
- The second type is a function pointer that specifically takes a reference to a MyStream object and returns a reference to the same object.
This allows for the implementation of a custom endl function that operates on the custom stream.
The above is the detailed content of How to Handle `std::endl` in Custom Stream Operator Overloading?. For more information, please follow other related articles on the PHP Chinese website!