【问题标题】:How to filter input streamed to clog如何过滤流入阻塞的输入
【发布时间】:2013-12-04 16:30:58
【问题描述】:

我目前正在尝试过滤流入“阻塞”流缓冲区的输入。因此,我想创建一个类“MyClog”,它重载它的

过滤取决于 MyClog 类的内部状态。另外我想使用模板重载运算符,所以我只需要实现一种方法。

例子

clog << "This is a Test No." << 1;

myclog << "This is a Test No." << 2

根据 myclog 的内部状态,消息通过 clog 打印出来。

如果我不使用模板,我的重载运算符可以工作,我做错了什么? template&lt;typename T&gt;template&lt;class T&gt;有什么区别?

这是我的代码的摘录。

template<typename T>
class MyClog {

private:
bool state=false;

public:
MyClog& operator<<(const T& arg){
    if(state){
        clog << arg;
    }
    return *this;
}

【问题讨论】:

标签: c++ templates filter overloading operator-keyword


【解决方案1】:

template&lt;typename T&gt; 优于 template&lt;class T&gt;,但它们是等价的。

当您只需要模板化一个函数时,您正在模板化整个类 - 这应该可以:

class MyClog {

private:
bool state=false;

public:

template<typename T>
MyClog& operator<<(const T& arg){
    if(state){
        clog << arg;
    }
    return *this;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-25
    • 2011-12-23
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多