1

I have a custom class called Stream

class Stream
public:
    Stream& operator<<(int i) { stream_ << i; return *this;}
            template <typename CustomClass>
            Stream& operator<<(const CustomClass& c) { stream_ << c.toString() /* assume this template always have toString(); return *this; }
private:
    std::stringstream stream_;
};

This is a very basic example of what I actually have. And I am trying to set std::ios_base flags like following:

Stream() << 1 << std::hex << 2;

using operator;

Stream& operator<<(std::ios_base& b) { stream_.setf(b.flags()); return *this; }

from what I understand, because std::hex returns std::ios_base so it should call this and set streams' flag. But it always call the template. Note: If i remove this template, everything works just as good as you would expect but is there a way to have both?

Please feel free to ask further if you need more clarification

David G
  • 94,763
  • 41
  • 167
  • 253
abumusamq
  • 780
  • 1
  • 10
  • 29
  • Just to clarify a bit more what I am trying is to make **ios_base** overloaded operator !important over template. I believe this is very weird behaviour since templates should be put at the very last if no other type could be resolved at compile time it should be used. and I believe std library is linked before all other libraries. – abumusamq Apr 15 '13 at 22:01
  • btw even if i return `std::ios_base&` and return stream, this does not do the job i mean it still calls template over typed overload – abumusamq Apr 15 '13 at 22:02

1 Answers1

0

IOStream manipulators are not objects of type std::ios_base, they are functions that take and return std::ios_base references. So when you want to do stream insertion regarding these objects, you have to overload for function pointers:

Stream& operator<<(std::ios_base& (*manip)(std::ios_base&))
//                 ^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^
{
    manip(this->stream);
    return *this;
}
David G
  • 94,763
  • 41
  • 167
  • 253