我有一些源自基本策略的策略。某些类专门用于派生策略,而其他类仅专门用于基本策略并且可以与所有派生策略一起使用。
我遇到的问题是代码重复太多(主要是类本身的构造函数和一些样板代码)。下面的代码可以更好地解释我的意思:
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
};
这是 SFINAE 的一个案例。
template< typename Policy, ...some_condition... >
struct Foo<Policy>
{
...
};
您应该准确地确定 some_condition 是什么。您可以指定 Policy 派生自 BasePolicy:
template< typename Policy, enable_if< is_base<BasePolicy, Policy> > >
或者您可以明确列出允许的策略:
template< typename Policy,
enable_if_c <is_same<Policy, BasePolicy>::value ||
is_same<Policy, DerivedPolicy1>::value> ||
...whatever...
>
>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)