2012-03-11 7 views
1

基本ポリシーから派生したポリシーがあります。一部のクラスは派生されたポリシーに特化しているクラスもあれば、基本ポリシーのみを専門とするクラスもあり、派生したすべてのポリシーで動作することができます。派生したすべてのポリシーのベースポリシーの作業に基づくテンプレートクラスの特殊化の取得

私が取り組んでいる問題は、あまりにも多くのコードの重複(主にコンストラクタとクラス自体のボイラープレートコード)です。以下のコードは、私が何を意味するかのより良い説明を提供することがあります。

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 (i.e. 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; 
}; 

は、基本方針に特化したクラスで受け入れられるために派生政策のための方法はありますか?私はクライアントに特別なことをしないことを望みます。

次は、有効なC++コードではなく、(あなたが心の中で上記のコードを続ければ)私はこのような何かが起こるたいと思います:

template<> 
struct Foo<BasePolicy | DerivedPolicy1 | DerivedPolicy2> 
{ 
    //... many constructors along with code 
}; 

答えて

3

これはSFINAEの場合です。

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

some_conditionを正確に決定する必要があります。

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

それとも、明示的ポリシー許可リストすることができます:あなたは、そのポリシーがBasePolicyから派生指定することができます

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

はちょうどこの同じ問題を越え、自分自身を実行しました。あなたは私と同様にそれを言った。 :) – Nick

+0

素晴らしい、まさに私が探していたもの。 – Samaursa

関連する問題