函数的重载流运算符
overload stream operator for function
我很好奇是否可以为函数重载<<
流运算符?
我在 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
编写更复杂的包装器类。 但这可能不值得付出努力。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板