使用简单的记录器来流操纵器

时间:2014-02-16 14:46:15

标签: c++ stream

所以我有这个简单的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,这对我来说似乎有点过分。还有更好的选择吗?

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

1 个答案:

答案 0 :(得分:1)

由于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;
}