我应该如何为采用数组的基类函数提供单个元素的便利函数

时间:2015-03-22 19:44:54

标签: c++ inheritance

假设我有一个基类声明一个纯虚函数do_sth()采用向量,但在派生类中通常只使用具有单个元素的向量。 因此,为了方便起见,我想提供一个带有单个元素的do_sth()的第二个版本。我不想在每个类派生中实现第二个版本 来自Base,因为它的目的只是调用带矢量的版本。因此我的想法是在基类中实现它,如下所示:

class Base {
    virtual void do_sth(const std::vector<int>& v) = 0;
    void do_sth(int n) {
        do_sth(std::vector<int>{n});
    }
};

class Derived : public Base {
    void do_sth(const std::vector<int>& v) override {
          //do_sth with v
    }
};

但是,这样一来,如果我的代码的用户想要调用带有单个元素的版本,他们必须通过指向基类的指针来完成它。 不是我想要的。

Derived* d = new Derived();
Base* b = new Derived();

d->do_sth(5); // compilation fails because Base::do_sth is hidden in Derived
d->do_sth({5}); // obviously works, but does not make use of convenience function

b->do_sth(5); // works, but requires the user to remember using a
              // pointer to base, e.g. he can't write 
              // auto b = make_shared<Derived>(); b->do_sth(5);
d->Base::do_sth(5); // works, but requires the user to remember
                    // to explicitly call the base class function 

我所知道的唯一其他选项是重新定义派生自Base的每个类中的便捷函数,如下所示:

void Derived::do_sth(int n) {
    Base::do_sth(n);
}

或放

using Base::do_sth 

在派生类中。 我不喜欢这个是我必须记住在每个类中编写redefinition / using语句 源于基地。

有人知道另一种可能更好的方法来实现我所寻求的功能吗?也许我应该选择另一种设计方案?

0 个答案:

没有答案
相关问题