基于条件覆盖 C++ 函数

Overriding C++ function based on conditional

所以我用了很长时间的 C,Java,但是我对 C++ 不是很熟悉。情况是我们有:

base class template 1 -> base class template 2 -> several relevant subclasses

目前所有的final subclass都继承了class1的一个成员函数,但是我们只需要在其中一个subclass中改变这个函数的行为es,并且仅当代码中其他地方的变量被设置时,否则 运行 class 中定义的函数 1. 有没有办法做到这一点而无需在另一侧插入整个函数定义if-else?我看过 SFINAE/enable-if,但它用于基于类型的决策,而不是像这样的简单条件。

如果我遗漏了任何容易或愚蠢的事情,请告诉我。

一些伪代码可能会有所帮助:

template <class Face> class Publisher {
  virtual void publish(...) {
    // do stuff
  }
}

template <class NewsType> class NewsPublisher : public Publisher<OnlineFace> {
  // constructors, destructors...
}

class MagazinePublisher : public NewsPublisher<Sports> {
  void publish(...) {
    if(that.theOther() == value) {
      // do different stuff
    } else {
      // do whatever would have been done without this override here
    }
  }
}

根据您的示例,您可以简单地显式调用基础 class 实现:

class MagazinePublisher : public NewsPublisher<Sports> {
  void publish(...) {
    if(that.theOther() == value) {
      // do different stuff
    } else {
      // call the base class implementation, as this function would not
      // have been overridden:
      NewsPublisher<Sports>::publish(...);
   // ^^^^^^^^^^^^^^^^^^^^^^^
    }
  }
}

嗯,我想你的实际基础 class 函数 publish() 被声明为 virtual 成员。


此外,由于您的示例只是伪代码,我无法真正测试它,您可能需要添加 NewsPublisher<T> class 中应使用哪个 publish() 实现:

template <class NewsType> class NewsPublisher : public Publisher<OnlineFace> {
public:
  // constructors, destructors...
  using Publisher<OnlineFace>::publish(); // <<<<<<<<<<<<<
}