为{0,1}参数重载预处理器宏

Overloading Pre-processor macros for {zero, one} arguments

本文关键字:重载 预处理 处理器 参数      更新时间:2023-10-16

我在c++中为我的应用程序制作一个记录器类。该类具有静态成员,用于将调试输出记录到文件中。我想创建一个可以以两种方式使用的宏:

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

——或

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

目标是包含Logger.h足以将日志记录到文件中,并且使用相同的语法完成,但如果您有其他建议,我不会特别依赖宏。不幸的是,不能使用Boost::PP。

我已经看了一下(见这个注释),但是没有发现任何关于区分LOG和LOG()调用的内容。我如何区分有论证和无论证?

可以重载Logger类的操作符,避免使用宏

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;
    }
};