如何创建如std :: cout的功能? [英] How to create functions like std::cout?

查看:193
本文介绍了如何创建如std :: cout的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的项目创建了自己的日志库,我想创建一个函数,如iostream的std :: cout,日志到一个文件,并打印到控制台。



这里是我想要的:

  enum 
{
debug,error,warning,info
};

LOG(level)<< 测试; // level - 从上面的枚举

EDIT:像这样:

  int iPlayerID = 1337; 
LOG(info)<< Player< iPlayerID<< 连接的;

[Thu Jan 29 18:32:11 2015] 1337已连接

解决方案

std :: cout 不是一个函数,它是一个类型 std :: ostream 的对象,它重载运算符<< p>

您可以如何做的快速草图:

 枚举级别{ 
debug,error,warning,info
};

struct Logger {
std :: ostream * stream; //在构造函数中设置此值,将
//指向文件或控制台流
级别debug_level;
public:
Logger& operator<<(const std :: string& msg)
{
* stream< msg; //也打印级别等。
return * this;
}

朋友Logger& log(Logger& logger,Level n);
{
logger.debug_level = n;
return logger;
}
};

Ant然后使用

  Logger l; 
log(l,debug)<< 测试;


I'm creating my own logging library for my project, I Want to create a function like iostream's std::cout, to log to a file and print to console also.

Here's what i want:

enum
{
    debug, error, warning, info
};

LOG(level) << "test"; // level - from the above enum

EDIT: The Result must be like this:

int iPlayerID = 1337;
LOG(info) << "Player " << iPlayerID << "Connected";

[Thu Jan 29 18:32:11 2015] [info] Player 1337 Connected

解决方案

std::cout is not a function, it's an object of type std::ostream which overloads operator<<.

A quick sketch of how you could do it:

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 then use it like

Logger l;
log(l, debug) << "test";

这篇关于如何创建如std :: cout的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆