这是mcve。它有效: -
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)
}
根据模板,从Enable class的成员中修改了上述MCVE,该模板一次只能启用一个字段。
(我阅读了这两个答案,但是其第二个解决方案使用了太多的内存。)
如何轻松地打开/关闭许多字段?
令人遗憾的是,这个McVe很快就变得混乱了。
在我的实际情况下,我有大约5-6个独特的字段,它们是不同类型的。
为简单起见,cat3
的类型,dog2
,...不依赖于t。
您可能有更简单的内容:
class Cat { public: int cat3; };
struct Dog { public: int dog2; };
struct Rat { public: int rat1; };
template <typename... Bases>
class Group : public Bases... {};
,然后
Group<Dog, Rat> h;
h.dog2=5;