c++ - 如何轻松覆盖多个重载方法?

标签 c++ templates decorator

假设我有一个接口(interface)和一个实现它的类,如下所示:

class IPrinter
{
public:
    virtual void print(int i, int base = 10) = 0;
    virtual void print(char c) = 0;
    virtual void print(char *s) = 0;
    virtual void print(float f) = 0;
    virtual void print(double d) = 0;
    virtual ~IPrinter() = default;
private:
    ...
}

class Printer : public IPrinter
{
public:
    void print(int i, int base = 10) override {...}
    void print(char c) override {...}
    void print(char *s) override {...}
    void print(float f) override {...}
    void print(double d) override {...}
private:
    ...
}

然后我决定添加一个简单的装饰器类,如下所示:

class SwitchablePrinter : public IPrinter
{
private:
    IPrinter& _printer;
    bool _enabled;
    ...
public:
    SwitchablePrinter(IPrinter& p) : 
        _printer(p), 
        _enabled(true) 
    {
    }

    void print_enable(bool on) { _enabled = on; }

    void print(int i, int base = 10) override
    {
        if (_enabled)
            _printer.print(i, base);
    }
    void print(char c) override
    {
        if (_enabled)
            _printer.print(c);
    }
    void print(char *s) override
    {
        if (_enabled)
            _printer.print(s);
    }
    void print(float f) override
    {
        if (_enabled)
            _printer.print(f);
    }
    void print(double d) override
    {
        if (_enabled)
            _printer.print(d);
    }
}

现在,所有这些都非常简单明了。 问题在于 SwitchablePrinter 实现中存在大量代码重复。我想知道,是否有一种方法可以为基类中的所有重载方法编写通用方法“print”,如下所示:

(pseudo-code)
void print({any args})
{
    if (_enabled)
        _printer.print({any args});
}

我认为可能有一个使用模板的解决方案,但我对使用它们不是很有经验,需要建议。

最佳答案

虽然没有同时覆盖多个成员函数的机制,但您可以通过提供一个私有(private)可变成员函数模板来简化您的任务并减少代码重复,该模板将调用转发到包装的 _printer,像这样:

private:
    template <class ... T>
    void print_impl(T ... vals) {
         if (_enabled)
             _printer.print(vals...);
         else
             cout << "disabled" << endl;
    }
public:
    void print(int i, int r) override {
        print_impl(i, r);
    }
    void print(float f) override {
        print_impl(f);
    }
    void print(double d) override {
        print_impl(d);
    }
    void print(char* s) override {
        print_impl(s);
    }
    void print(char c) override {
        print_impl(c);
    }

Demo.

这只是在原来的基础上稍作改进,因为print_impl的转发逻辑非常简单。当逻辑变得更加复杂时,共享代码的返回就会增加。

关于c++ - 如何轻松覆盖多个重载方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33213719/

相关文章:

c++ - 作为模板参数的指针 vector

c++ - 定义非静态成员时在 C++ 中获取 "this"的类型

c++ - Itk: ImageRegionIterator GetIndex() 调用使程序出现段错误

c++ - POD 结构或标准布局类型的成员是否保证根据其对齐要求对齐?

c++ - ARM 上的预取指令

c++ - 模板扣减申诉模棱两可的候选人

具有多个参数的 python 装饰函数(Tornado)

带有可选参数(即函数)的 Python 装饰器

python - Jython @property 语法错误 : mismatched input '' expecting CLASS

c++ - 将指针数组初始化为空指针