Obtaining a core policy class specialization for all derived policies

I have policies based on a basic policy. Some classes specialize in derived policies, while others specialize only in basic policies and can work with all derived policies.

The problem I am facing is too much code duplication (mostly constructors and some boiler plate code for the class itself). The code below may give a better explanation of what I mean:

struct BasePolicy {}; struct DerivedPolicy1 : public BasePolicy {}; struct DerivedPolicy2 : public BasePolicy {}; //... more policies deriving from BasePolicy (or other BasePolicies) struct AnotherPolicy {}; template <typename T> struct Foo; // This struct can work for all BasePolicy types which includes all derivations // of it (but doesn't because it is specialized for BasePolicy only) template<> struct Foo<BasePolicy> { //... many constructors along with code }; template<> struct Foo<AnotherPolicy> { //... more code }; /* Would like to avoid the following code as it duplicates the above when it comes to constructors and other things such as typedefs */ //template<> //struct Foo<DerivedPolicy1> : Foo<BasePolicy> //{ // //... same constructors as Foo<BasePolicy> //}; // //template<> //struct Foo<DerivedPolicy2> : Foo<BasePolicy> //{ // //... same constructors as Foo<BasePolicy> //}; int main() { // would like this to compile without uncommenting the commented out code and // without having the client (ie the line below) to somehow get the base // type of the policy (although if it can be done transparently, that will // work) Foo<DerivedPolicy1> a; }; 

Is there a way in which a derived policy can be adopted by a class specialized for a basic policy? I would like the client not to do anything extra.

Invalid C ++ code, but I would like this to happen (if you remember this above):

 template<> struct Foo<BasePolicy | DerivedPolicy1 | DerivedPolicy2> { //... many constructors along with code }; 
+1
source share
1 answer

This applies to SFINAE.

 template< typename Policy, ...some_condition... > struct Foo<Policy> { ... }; 

You must determine exactly what some_condition is. You can indicate that the policy comes from BasePolicy:

 template< typename Policy, enable_if< is_base<BasePolicy, Policy> > > 

Or you can explicitly specify valid policies:

 template< typename Policy, enable_if_c <is_same<Policy, BasePolicy>::value || is_same<Policy, DerivedPolicy1>::value> || ...whatever... > > 
+3
source

All Articles