问题描述
限时送ChatGPT账号..我有源自基本政策的政策.一些类专用于派生策略,而其他类仅专用于基本策略并可与所有派生策略一起使用.
I have policies that derive from a base policy. Some classes specialize for the derived policies while others specialize only for the base policy and can work with all derived policies.
我遇到的问题是代码重复太多(主要是类本身的构造函数和一些样板代码).下面的代码可以更好地解释我的意思:
The problem I am running into is too much code-duplication (mainly constructors and some boiler plate code for the class itself). The code below may provide a better explanation of what I mean:
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;
};
有没有办法让专门用于基本策略的类接受派生策略?我希望客户不要做任何额外的事情.
Is there any way for a derived policy to be accepted by a class specialized for the base policy? I would like the client to not do anything extra.
以下不是有效的 C++ 代码,但我希望这样的事情发生(如果您记住上面的代码):
The following is not valid C++ code, but I would like something like this happen (if you keep the above code in mind):
template<>
struct Foo<BasePolicy | DerivedPolicy1 | DerivedPolicy2>
{
//... many constructors along with code
};
推荐答案
这是 SFINAE 的案例.
This is a case for SFINAE.
template< typename Policy, ...some_condition... >
struct Foo<Policy>
{
...
};
您应该确切地确定 some_condition 是什么.您可以指定 Policy 派生自 BasePolicy:
You should decide what is some_condition exactly. You can specify that Policy derives from BasePolicy:
template< typename Policy, enable_if< is_base<BasePolicy, Policy> > >
或者您可以明确列出允许的政策:
Or you can list allowed policies explicitly:
template< typename Policy,
enable_if_c <is_same<Policy, BasePolicy>::value ||
is_same<Policy, DerivedPolicy1>::value> ||
...whatever...
>
>
这篇关于根据所有派生策略的基本策略工作获取模板类专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论