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
};
过这个同样的问题,刚跑到自己;你尽可能地说了。 :) – Nick 2012-03-11 05:40:26
非常好,正是我所期待的。 – Samaursa 2012-03-11 22:22:04