C++ – Overloading << to define manipulators

coperator-overloading

I found this question on archived file at joelonsoftware.com http://discuss.joelonsoftware.com/default.asp?joel.3.594503.11

"Hi,

I'm having a particularly slow day and
can't get my head round an operator
overloading problem. I would like a
class to be able to accept data via an
insertation operator, i.e:

myClassInstance << std::string("a
string") << 4 << 3.4 << std::endl;

Internally, I'd like everything to end
up in a stringstream so I can then
farm it off to other streams (say
std::cout and an ofstream). I have got
horribly confused how I can do this
without having to write an operator<<
overload for every data type, and how
an input stream would be created on
the first call (myClassInstance <<
…).

Any help gratefully received!"

This is exactly what I am trying to do. I have found my way to deal with all types by defining templates and another overloaded method to deal with manipulators like endl defined in ostream class.

UIStream&  UIStream ::operator << (const T str)
 {
     CString cstr(stringify(str).c_str());
     theFrame->m_pOutputView->WriteMessage(cstr);
     return *this;
 }

 //for manipulators like std::endl
UIStream&  UIStream ::operator <<(ostream& (*m)(ostream&))
{
     //stream<<*m; 
     //CString cstr((*m)(new ostream).c_str());
    if(*m==&std::endl);
        theFrame->m_pOutputView->WriteMessage("\n");
     return (*this);
}

I am still struggling with manipulators that take arguments like hex dec or oct this are defined in ios_base.

Best Answer

Probably an idea to read a good book on the topic. I recommend Standard C++ IOStreams and Locales by Langer and Kreft.