How to support std::endl

For the customized stream class it might be useful.
If you are making a customized stream class you might think that supporting standard

 std::endl
 std::flush

is essential.

The following fragment shows how to implement this feature.

#include <iostream>
using namespace std;
typedef std::ostream& (*Manipulator)(std::ostream&);
class mystream{
public:
        mystream & operator <<(const std::string &str){
                std::cout << str.c_str();
                return *this;
        }
        mystream & operator<<(Manipulator man)
        {
                std::cout << man;
                return *this;
        }
};

int main(int argc, char * argv[]){
        mystream x;
        x << "x" << std::endl << "y" << std::endl << std::flush;
        return 0;
};

This works on both VS 7.1 and g++ (3.2.3) because manipulators like std::endl are implemented as functions. Thus your custom stream class must support operator << which takes a pointer to function as a parameter.

Leave a Reply