多态函数调用没有重复代码

Alw*_*ing 8 c++ polymorphism

假设层次结构的所有类都实现了模板成员函数g.所有类共享两个其他函数的相同实现,f1f2调用此模板:

struct A {
    virtual void f1() {
        g(5);
    }
    virtual void f2() {
        g(5.5);
    }
private:
    template <typename T> void g(T) {std::cout << "In A" << std::endl;}
};

struct B: A {
    // Can I get rid of this duplicate code?
    virtual void f1() {
        g(5);
    }
    virtual void f2() {
        g(5.5);
    }
private:
    template <typename T> void g(T) {std::cout << "In B" << std::endl;}
};

struct C: A {
    // Can I get rid of this duplicate code?
    virtual void f1() {
        g(5);
    }
    virtual void f2() {
        g(5.5);
    }
private:
    template <typename T> void g(T) {std::cout << "In C" << std::endl;}
};

int main()
{
    B b;
    A &a = b;
    a.f1();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

由于所有类的实现f1f2相同,我如何摆脱重复的代码,仍然main按预期工作的多态调用(即产生输出"在B中")?

Rei*_*ica 3

请注意, 、 、f1f2中和的实现并不相同。让我们将其限制为s。第一个调用名为 的函数,另一个调用名为 的函数,第三个调用名为 的函数。它们相差甚远ABCf1::A::g<int>::B::g<int>::C::g<int>

你能做的最好的事情就是拥有一个CRTP风格的基础:

template <class Derived>
struct DelegateToG : public A
{
  void f1() override
  {
    static_cast<Derived*>(this)->g(5);
  }

  void f2() override
  {
    static_cast<Derived*>(this)->g(5.5);
  }
};

class B : public DelegateToG<B>
{
  friend DelegateToG<B>;
private:
  template <class T> void g(T) { /*...*/ }
};

class C : public DelegateToG<C>
{
  friend DelegateToG<C>;
private:
  template <class T> void g(T) { /*...*/ }
};
Run Code Online (Sandbox Code Playgroud)