Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally to choose which classes to inherit

So, I've got a diamond hierarchy.

class Base {
    // ...
}
    
class Derived_A : public Base {
    // ...
}
    
class Derived_B : public Base {
    // ...
}
    
class Join : public Derived_A, public Derived_B {
    // ...
}

Depending on a template variable, I would like to conditionally choose to inherit A and/or B. (I understand with the diamond structure, A and B can be virtually inherited.) What I have exactly is:

template<bool HAS_A, bool HAS_B>
class Join : public Derived_A, // enable if HAS_A
             public Derived_B  // enable if HAS_B
{
    // ...
}

I attempted to use std::enable_if_t, but I am not sure that will work when the boolean to it is false.

like image 825
Blizzard Avatar asked Dec 30 '25 12:12

Blizzard


1 Answers

Specifying the base classes instead of using bool as template parameter seems more straightforward. e.g.

template<class... Base> class Join : public Base... {}; 

then use it like Join<Derived_A, Derived_B>, Join<Derived_A>, Join<Derived_B>, and Join<> (inherit nothing).

like image 117
songyuanyao Avatar answered Jan 01 '26 03:01

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!