2

I am creating a wrapper class around std::ofstream. I have override all the std::ofstream methods. Now, I need to override the std::endl method to use the wrapper class instead of basic_ostream.

Is it possible to override std::endl method? Can anyone give me an example?

Mat
  • 202,337
  • 40
  • 393
  • 406
veda
  • 6,416
  • 15
  • 58
  • 78
  • 3
    There's no class to override it in. `std::endl` is a free function. – cHao May 21 '13 at 18:38
  • 2
    Look at this question: http://stackoverflow.com/questions/2212776/overload-handling-of-stdendl – Tommy Andersen May 21 '13 at 18:38
  • 3
    `std::ofstream` has hardly any virtual functions so there is not a lot to override. (Deriving from `std::ofstream` is not usually a good way to implement extending functionality.) Why doesn't `std::endl` work with your new class is? If you want to do something different, why not just write a new function. What are you trying to achieve? – CB Bailey May 21 '13 at 19:32

2 Answers2

3

First: You are never allowed to overload functions in the ::std namespace. In fact, you are only allowed to specialize existing templates in the ::std namespace and that only with restrictions.

You can however deal with the endl situation by reading what it actually does in C++11 27.7.3.8/1:

Effects: Calls os.put(os.widen(’\n’)), then os.flush().

Therefore, you need to override nothing, just provide the correct member functions to deal with this sequence of put, widen and flush.

danielschemmel
  • 10,885
  • 1
  • 36
  • 58
  • None of `put`, `widen` or `flush` are virtual in `std::basic_ostream` or its bases and as `endl` is templated on the character type and not the stream type, providing versions of these functions in a class derived from `std::ostream` is pointless. – CB Bailey May 21 '13 at 19:38
  • I was assuming the OP was wrapping `ofstream` and inheriting `streambuf`, since he stated to have successfully "overridden" the `ofstream` methods. – danielschemmel May 21 '13 at 20:23
1

You could override operator<< for the type of std::endl, then check inside the overload whether you were passed std::endl. However: I don't think what you are doing is smart, although without really knowing what you want to achieve, it's hard to suggest a better approach. I'd say you should describe what your goal is instead of asking how to achieve a certain (flawed) solution.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55