overloading all <<oerators in ostream

Hi everyone,
I want to overload all <<operators in a class which inherits from ostream (to do some action before and/or after printing). What is the best way to do this?
I already tried to overload _M_insert (see line 366 in ostream: http://gcc.gnu.org/onlinedocs/gcc-4.6.3/libstdc++/api/a00967_source.html )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//in Console.h
class Console: public ostream
{
   protected:
   template<typename _ValueT>
      ostream& _M_insert(_ValueT __v);
...
};
extern Console fcout;
//in Console.cpp
template<typename _ValueT> ostream& Console::_M_insert(_ValueT __v)
{
    //return this->ostream::_M_insert(__v);
}
Console fcout;

But then nothing happens (as the function would never be overloaded)
I also tried this (overloading the "<<" with a template):
1
2
3
4
5
6
7
8
//Console.h
template<typename _ValueT> Console& operator<<(_ValueT __v);
//Console.cpp
template<typename _ValueT> Console& Console::operator<<(_ValueT __v)
{
    //this->ostream::_M_insert(__v);
    return fcout;
}

But then I'm getting lots of undefined references (one for each fcout << ...)
So I hope you can help me.

Thanks in advice!
Last edited on
Are you sure you need to inherit ostream? If you are making a console wouldn't composition make more sense? At any rate maybe something like template<typename _ValueT> Console& Console::operator<<(Console& fcout, _ValueT __v)
_M_insert is an implementation detail of your library, it's not a part of the streams interface.

ostream's operator<<'s aren't virtual (and many of them aren't even members), so any function that deals with your stream through std::ostream& will use the original operator<<'s.

What is your intended use case? If it's just something like
1
2
mystream s(sink);
s << "example: " << n << '\n';

you could store std::ostream& as a member of mystream and provide one non-member template operator<< for mystreams, perhaps with specializations as necessary.

For complex I/O streams filtering, take a look at boost.iostreams

EDIT: too slow!
Last edited on
It is not a good/smart idea to create/have a class inheriting from ostream, instead your class should contain a function(an overloaded function, need not to be a member of your class, it might be a friend function, or just a function which use public method of your class) which wraps and returns the result to the caller
Topic archived. No new replies allowed.