首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >一种简单记录器的流控机械手

一种简单记录器的流控机械手
EN

Stack Overflow用户
提问于 2014-02-16 14:46:15
回答 1查看 161关注 0票数 2

所以我有一个简单的C++日志类。

代码语言:javascript
运行
复制
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;

我可以这样用它:

代码语言:javascript
运行
复制
Log(1)<<"My debug info: "<<otherVariable;

问题是当我尝试使用endl

代码语言:javascript
运行
复制
Log(1)<<"My debug info: "<<otherVariable<<endl;

我知道这个错误:

代码语言:javascript
运行
复制
error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'Log' (or there is no acceptable conversion)

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

代码语言:javascript
运行
复制
// For manipulators like endl
Log& operator<< (ostream& (*pf) (ostream&)) {
    if (msgLevel<=level) {
        cout << pf;
    }

    return *this;
}

但是添加这个方法仅仅是为了处理endl,对我来说似乎有点过分了。还有什么更好的选择吗?

另一种选择是使用"\n“而不是endl;

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-16 15:11:22

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

但是,您可以将常见的逻辑分解出来,如:

代码语言:javascript
运行
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21812676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档