Home > Backend Development > C++ > How to Handle `std::endl` in Custom Stream Operator Overloading?

How to Handle `std::endl` in Custom Stream Operator Overloading?

DDD
Release: 2024-12-08 08:26:12
Original
237 people have browsed it

How to Handle `std::endl` in Custom Stream Operator Overloading?

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";
Copy after login

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
{
    template 
    MyStream& 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template