c – 基于所有派生策略的基本策略工作获取模板类专业化
作者:互联网
我的政策来自基本政策.某些类专门用于派生策略,而其他类专门用于基本策略,可以使用所有派生策略.
我遇到的问题是代码重复太多(主要是构造函数和类本身的一些样板代码).下面的代码可以更好地解释我的意思:
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...
>
>
标签:c,templates,code-duplication 来源: https://codeday.me/bug/20190902/1790483.html