gpt4 book ai didi

c++ - 获取基于基本策略的模板类特化适用于所有派生策略

转载 作者:太空狗 更新时间:2023-10-29 20:45:46 25 4
gpt4 key购买 nike

我有从基本策略派生的策略。一些类专用于派生策略,而其他类仅专用于基本策略并且可以与所有派生策略一起使用。

我遇到的问题是代码重复太多(主要是类本身的构造函数和一些样板代码)。下面的代码可以更好地解释我的意思:

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++ - 获取基于基本策略的模板类特化适用于所有派生策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9652531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com