0
votes

I'm making a logger class for my app in C++. This class has static members to log debug output to file. I would like to create a Macro that can be used in two ways:

LOG("Log some text")
          which calls Logger::log(std::string)

-----or-----

LOG << "Log some text" << std::endl;
          which calls Logger::getLogStream()

The goal being that including Logger.h be enough to log to file, and that it be done using the same syntax, but I'm not particularly attached to Macros if you have other suggestions. Using Boost::PP is, unfortunately, not an option.

I've looked around (see this comment), but found nothing concerning differentiating between a call to LOG and LOG(). How can I differentiate one argument from no arguments?

1
You can't. The pre-processor may be a part of the compiler, but it doesn't follow the rules of C or C++ languages, it's a completely different language, with different syntax and different semantic rules.Some programmer dude
Yeah I had figured, since I searched and found no way. Any other suggestions to accomplish this? Typedefs, inlines, macros, or something I might have missed?Robin Eisenberg
You can define a function-like macro LOG(X) and an object named LOG. The form LOG without parentheses is not affected by the expansion of the function-like macro. It is also possible to define a function object that overloads both operator() and operator<<.dyp

1 Answers

3
votes

You can overload operators of Logger class and avoid using macros

class Logger
{
  public:

    void operator( )( const std::string& ar_text )
    {
      log( ar_text );
    }

    Logger& operator<<( const std::string& ar_text )
    {
      // use logStream here
      return *this;
    }

    Logger& operator<<(std::ostream& (*f)(std::ostream&)) // This is necessary for grabbing std::endl;
    {
      // use logStream here
      return *this;
    }
};