yohannist
yohannist

Reputation: 4204

error while making custom cout

I am trying to make a custom cout class that outputs text to console output and log file when i try to run a version of this code that does not handle chaining (out<<"one"<<"two") it works fine, but when i try to make it handle chaining it gives me "too many parameters for this operator function". What am i missing?

class CustomOut
{
    ofstream of;

public:
   CustomOut()
   {
     of.open("d:\\NIDSLog.txt", ios::ate | ios::app);
   }

   ~CustomOut()
   {
     of.close();
   }

   CustomOut operator<<(CustomOut& me, string msg)
    {
    of<<msg;
    cout<<msg;

    return this;
}};

Upvotes: 3

Views: 115

Answers (1)

mavam
mavam

Reputation: 12552

You need a member operator<< which returns a reference to the object instance:

class CustomOut
{
  ...

  CustomOut& operator<<(string const& msg)
  {
    // Process message.
    f(msg);

    return *this;
  }
};

This will allow you to "stream" into your CustomOut class in a chaining manner:

CustomOut out;
out << str_0 << str_i << ... << str_n;

Upvotes: 5

Related Questions