Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally inherit from pure base class

Suppose I have the following class definitions

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

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

struct B: public base {
  int f() final { return 2; }
};

Is it possible to turn A and B into templates that take a bool parameter that specifies whether to inherit from the base or not? I have usage cases that do or don't require a base class providing a common interface.

Assume that A and B have a lot of member functions, so duplicating implementation would be tedious. But sizeof(A) and sizeof(B) are small.

like image 947
SU3 Avatar asked Jan 14 '17 00:01

SU3


1 Answers

Sure:

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

template <> struct A<true> : base
{
    // ...
};

(Note that you could make A<true> derive from A<false> if that avoids redundancy.)

For example:

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();
}
like image 164
Kerrek SB Avatar answered Oct 03 '22 20:10

Kerrek SB