有条件(SFINAE)覆盖 [英] conditional (SFINAE) override
问题描述
我正在尝试这样做:
struct A
{
virtual int f() const { return 0; }
};
template <typename T>
struct B : A
{
template <typename U = T,
typename std::enable_if<...some condition involving U...>::type>
int f() const { return 1; }
};
注意,我不能继承类模板(使用静态替代)。
Caveat, I can't inherit class templates (use static overrides). Is this sort of construct allowed and can the template member B::f() override the member A::f()?
推荐答案
<?是否允许这种构造,并且模板成员B :: f()是否可以覆盖成员A :: f()? p>尝试一下:
Try this:
template <typename T, typename=void>
struct B : A
{
...
};
temlate <typename T>
struct B<T, typename std::enable_if<...some condition...>::type>:
A
{
virtual int f() const override { return 1; }
};
其中我们有两个版本的 B< T>
,条件为真的一个( enable_if
一个),条件为假的一个(默认一个)。
where we have two versions of B<T>
, one for which the condition is true (the enable_if
one), one for which the condition is false (the default one).
如果您希望能够重用默认的 B
实现,则可以执行以下操作:
If you wanted to be able to reuse your default B
implementation, you could even do this:
template <typename T, typename=void>
struct B : A
{
...
};
template <typename T>
struct B<T, typename std::enable_if<...some condition...>::type>:
B<T, bool>
{
virtual int f() const override { return 1; }
};
在 true情况下,我们从 false情况继承。但这对我来说有点肮脏-我宁愿将通用实现放在第三点( B_impl
),而不是黑手。 (这也使您可以静态断言,在第一种情况下 B
,第二个参数是 void
)。
where we inherit from the "false" case in the "true" case. But that is a bit dirty to me -- I'd rather put the common implementation in some third spot (B_impl
) rather than that hack. (That also lets you static assert that the second argument is void
in the first case of B
).
这篇关于有条件(SFINAE)覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!