且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

虚拟继承和静态继承 - 在C ++中混合

更新时间:2023-09-17 23:15:58

我不知道我明白你在问什么,但它似乎你缺少必要的CRTP转型:

I'm not sure I understand what you're asking, but it appears you are missing the essential CRTP cast:

template<class T>
struct A {
  void func() {
    T& self = *static_cast<T*>(this);  // CRTP cast
    self.func();
  }
};

struct V : A<V> {  // B for the case of virtual func
  virtual void func() {
    std::cout << "V::func\n";
  }
};

struct NV : A<NV> {  // B for the case of non-virtual func
  void func() {
    std::cout << "NV::func\n";
  }
};

如果T不声明自己的func,这将是无限递归self.func会找到A< ; T> :: func。即使一个T的派生类(例如下面的DV)声明了它自己的函数,但T不是。

If T does not declare its own func, this will be infinite recursion as self.func will find A<T>::func. This is true even if a derived class of T (e.g. DV below) declares its own func but T does not.

测试与不同的最终超控显示发布工作作为广告:

Test with different final overrider to show dispatch works as advertised:

struct DV : V {
  virtual void func() {
    std::cout << "DV::func\n";
  }
};
struct DNV : NV {
  void func() {
    std::cout << "DNV::func\n";
  }
};

template<class B>
void call(A<B>& a) {
  a.func();  // always calls A<T>::func
}

int main() {
  DV dv;
  call(dv);   // uses virtual dispatch, finds DV::func
  DNV dnv;
  call(dnv);  // no virtual dispatch, finds NV::func

  return 0;
}