Overloading operator<< with Custom endl Handling
When overloading the operator<< operator, it's possible to encounter compilation errors when attempting to use std::endl. This error occurs because the compiler cannot find an appropriate operator<< implementation to handle the std::endl type.
To resolve this, it's necessary to understand that std::endl is not an object, but rather a function. To accommodate this, std::cout has its own operator<< overload that specifically takes a function pointer with the same signature as std::endl. When called, this overload invokes the function and propagates the return value.
To enable custom streams to handle std::endl, a similar approach is required. Here's an example code that demonstrates this:
#includestruct MyStream { template MyStream& operator<<(const T& x) { std::cout << x; return *this; } // Function that takes a custom stream and returns it typedef MyStream& (*MyStreamManipulator)(MyStream&); // Overload to accept functions with custom signature MyStream& operator<<(MyStreamManipulator manip) { return manip(*this); } // Custom `endl` implementation for this stream static MyStream& endl(MyStream& stream) { std::cout << std::endl; stream << "Called MyStream::endl!" << std::endl; return stream; } // Type of std::cout typedef std::basic_ostream > CoutType; // Function signature of std::endl typedef CoutType& (*StandardEndLine)(CoutType&); // Overload to accept std::endl MyStream& operator<<(StandardEndLine manip) { manip(std::cout); return *this; } }; int main() { MyStream stream; stream << 10 << " faces." << MyStream::endl << std::endl; return 0; } In this code, we have:
- Overloaded operator<< for MyStream to handle generic types and functions with a custom signature.
- Defined a custom endl function that prints a new line and additional information.
- Overloaded operator<< for MyStream to accept std::endl's function pointer as an argument.
This approach allows custom streams, like MyStream in the example, to support std::endl and provide custom behaviors when using it.
The above is the detailed content of How to Handle `std::endl` When Overloading the `. For more information, please follow other related articles on the PHP Chinese website!