我正在为我的项目创建自己的日志实用程序,我想创建一个类似于 iostream 的 std::cout 的函数,以记录到文件并打印到控制台。
这是我想要的:
enum
{
debug, error, warning, info
};
LOG(level) << "test"; // level - from the above enum
结果应该是这样的:
int iPlayerID = 1337;
LOG(info) << "Player " << iPlayerID << "Connected";
[2015 年 1 月 29 日星期四 18:32:11] [信息] Player 1337 已连接
最佳答案
std::cout
不是函数,它是 std::ostream
类型的对象重载 operator<<
.
如何做的快速草图:
enum Level {
debug, error, warning, info
};
struct Logger {
std::ostream* stream; // set this in a constructor to point
// either to a file or console stream
Level debug_level;
public:
Logger& operator<<(const std::string& msg)
{
*stream << msg; // also print the level etc.
return *this;
}
friend Logger& log(Logger& logger, Level n);
{
logger.debug_level = n;
return logger;
}
};
Ant 然后像这样使用它
Logger l;
log(l, debug) << "test";
关于c++ - 如何创建像 std::cout 这样的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28217643/