繁体   English   中英

带有简单Logger的流操纵器

[英]Stream manipulator with a simple Logger

所以我有这个简单的C ++ Logger类。

class Log{
public:
    Log(const int& msgLevel = 1){
        this->msgLevel = msgLevel;
    }

    template <class T>
    Log& operator<<(const T& v){
        if (msgLevel<=level) {
            std::cout << v;
        }
        return *this;
    }

    ~Log(){

    }

    static int level;
    int msgLevel;
};

int Log::level = 1;

我可以这样使用它:

Log(1)<<"My debug info: "<<otherVariable;

问题是当我尝试使用endl

Log(1)<<"My debug info: "<<otherVariable<<endl;

我收到此错误:

error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'Log' (or there is no acceptable conversion)

要解决此错误,我需要向类中添加另一个方法,如下所示:

// For manipulators like endl
Log& operator<< (ostream& (*pf) (ostream&)) {
    if (msgLevel<=level) {
        cout << pf;
    }

    return *this;
}

但是,添加此方法只是为了处理endl ,对我来说似乎有点矫kill过正。 还有更好的选择吗?

另一种选择是仅使用“ \\ n”代替endl;

因为endl是函数模板,所以operator<<的简单版本还不够好,因为可以通过对endl使用不同的模板参数来匹配多种可能的方式。 添加第二个过载可能是您可以做的最好的事情。

但是,您可以考虑如下通用逻辑:

template <class T>
Log& operator<<(const T& v){ return write(v); }

Log& operator<<(ostream& (*v)(ostream&)){ return write(v); }


template <typename T>
Log& write(const T &v)
{
    if (msgLevel<=level) {
        std::cout << v;
    }
    return *this;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM