Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable Arguments by overloading << with a seperate argument.

Status
Not open for further replies.
Jan 20, 2005
180
US
Im looking for a way to pass variable arguments by overloading the << operator.

Basically, making a cout function that has a parameter passed to it.

I know how to do this with stdarg/varargs however this isnt the functionality I am looking for.

I have a class that is going to handle logging for a growing application.

This logging class handled multiple different types of log messages. There are 2 functions in this class that I need to access the overloaded operator.
Log and Debug.

The end result would be doing something like this...
char v[1024];
LOG lp(..);

sprintf(v, "my log message");
lp.Log(ERROR, v);

Im basically looking to move those 2 together with the overload operator so I would be able to do something like this.

lp.Log(ERROR) << "my log message";

How do I go about doing this? and/or Where can I find some help docs on this. I have yet to find any.
 
A way to do this is to define a Log class and some descedants for Error, Warning, etc. :

Code:
class Log
{
public:
  Log (const String& message) :
    _message (message)
  {
  }

  virtual String text () const = 0;

protected:
  String _message;
};


class ErrorLog
{
public:
  ErrorLog (const String& message) : 
    Log (message)
  {
  }

  // -- from Log.
  String text () const
  {
    return "Error : " + _message;
  }
};

// Define DebugLog, WarningLog, FatalLog, etc. from class Log.


A dummy Logger class with operator<< :
Code:
class Logger
{
public:
  Logger& operator<< (const Log& log)
  {
    _out_stream << log.text ();
    return *this;
  }

private:
  TextStream _out_stream;
};


Client code typically do :
Code:
Logger logger;
logger << ErrorLog ("An error log")
       << WarningLog ("A warning log")
       << DebugLog ("A debug log");


--
Globos
 
Globos,
How would I then make the error message thats being sent a variable number of arguments?

like a sprintf,
sprintf(charvar, "Message - %i, %s", intvar, charvar2);
 
You can use operator << for that purpose instead of the C printf style :
Code:
#include <iostream>
#include <strstream>
using namespace std;

int main ()
{
  int intvar = 150;
  strstream str_stream;
  str_stream << "Message - " << intvar << ", some text";
  cout << str_stream.str () << endl;

  return 0;
}

--
Globos
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top