有条件地继承纯基类

SU3*_*SU3 5 c++ inheritance templates c++14

假设我有以下类定义

struct base {
  virtual int f() = 0;
};

struct A: public base {
  int f() final { return 1; }
};

struct B: public base {
  int f() final { return 2; }
};
Run Code Online (Sandbox Code Playgroud)

是否有可能把AB成需要的模板bool,它指定参数是否从继承base与否?我有一些用例,它们需要或不需要提供通用接口的基类.

假设A并且B具有许多成员函数,因此重复实现将是乏味的.但是,sizeof(A)sizeof(B)小.

Ker*_* SB 5

当然:

template <bool> struct A
{
    // ...
};

template <> struct A<true> : base
{
    // ...
};
Run Code Online (Sandbox Code Playgroud)

(请注意,如果避免冗余,您可以A<true>从派生A<false>。)

例如:

template <bool> struct A
{
    void f() { std::cout << "A::f called\n"; }
};

template <> struct A<true> : A<false>, base
{
    void f() override { A<false>::f(); }
};

int main()
{
    A<false> a1;
    A<true> a2;
    a1.f();
    a2.f();
    static_cast<base&>(a2).f();
}
Run Code Online (Sandbox Code Playgroud)


SU3*_*SU3 4

我想出了我正在寻找的更直接的方法,无需重复代码。

struct base {
  virtual int f() = 0;
};

struct empty_base { };

template <bool Inherit>
struct A final: public std::conditional_t<Inherit,base,empty_base> {
  int f() { return 1; }
};
Run Code Online (Sandbox Code Playgroud)