函数的重载流运算符

overload stream operator for function

本文关键字:运算符 重载 函数      更新时间:2023-10-16

我很好奇是否可以为函数重载<<流运算符?

我在 Windows 上使用OutputDebugString写入日志,它只接受字符串。

我想知道我是否可以用 c++ 编写一个函数,我可以在其中包装OutputDebugString并执行以下操作

MyLogFuntion() << string << int << char;

您可以从具有operator <<的函数中返回一个对象,然后在该对象的析构函数中进行日志记录。然后,当您调用MyLogFunction()时,它将创建一个临时对象,该对象将存储插入其中的所有数据,然后在语句末尾的对象超出范围时输出它。

这是一个示例(没有实际上是多余的记录器功能(

#include <iostream>
#include <sstream>

class Logger {
    std::stringstream ss;
public:
    ~Logger() {
      // You want: OutputDebugString(ss.str()); 
      std::cout<< ss.str(); 
    }
    // General for all types supported by stringstream
    template<typename T>
    Logger& operator<<(const T& arg) {
       ss << arg;
       return *this;
    }
    // You can override for specific types
    Logger& operator<<(bool b) {  
       ss << (b? "Yep" : "Nope");
       return *this;
    }
};

int main() {
    Logger() << "Is the answer " << 42 << "? " << true;
}

输出:

答案是42吗?是的

您不能以您想要的方式提供重载。

如果您必须使用的方法(在您的情况下OutputDebugString(强制您提供std::string(或类似(参数,则必须以某种方式提供该参数。 一种方法是使用 std::stringstream ,流式传输到该OutputDebugString

std::stringstream ss;
ss << whatever << " you " << want << to << stream;
OutputDebugString(ss.str());

如果你真的想要更紧凑的东西,你也可以把它转储到宏中:

#define OUTPUT_DEBUG_STRING(streamdata)   
  do {                                    
    std::stringstream ss;                 
    ss << streamdata;                     
  } while (0)

然后写

OUTPUT_DEBUG_STRING(whatever << " you " << want << to << stream);

另一种选择是围绕提供流运算符的 OutputDebugString 编写更复杂的包装器类。 但这可能不值得付出努力。