Search code examples
c++templatesc++17enable-if

enable MANY class's member fields at once, depending on template <T>


Here is MCVE. It works :-

template<bool c3> class Has3 { };
template<> class Has3<true> { public: int cat3; };

template<bool c2,bool c3> class Has2 : public Has3<c3>{ };
template<bool c3> struct Has2<true,c3> : public Has3<c3>{ public: int dog2; };

template<bool c1,bool c2,bool c3> class Has1 : public Has2<c2,c3>{ };
template<bool c2,bool c3> struct Has1<true,c2,c3> : 
     public Has2<c2,c3>{public:  int rat1; }; //<- ugly, in my opinion.

int main(){
    Has1<false,true,false> h; 
    h.dog2=5;
    //h.cat3=4;  //<- compile error (which is good)
}

The above inelegant MCVE is modified from enable class's member depending on template, which can enable only one field at a time.
(I read both answers, but its second solution uses too much memory.)

How to toggle many fields on/off easily?
It is sad that this MCVE becomes a mess pretty fast.

In my real cases, I have about 5-6 unique fields, that are different types.
For simplicity, the type of cat3,dog2,... does not depend on T.


Solution

  • You might have something simpler with:

    class Cat  { public: int cat3; };
    struct Dog { public: int dog2; };
    struct Rat { public: int rat1; };
    
    template <typename... Bases>
    class Group : public Bases... {};
    

    And then

    Group<Dog, Rat> h;
    
    h.dog2=5;