enable_if中的短路运算符 [英] Short Circuiting Operators in an enable_if

查看:112
本文介绍了enable_if中的短路运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个使用 array< int,3> int [3] 。我试图在 enable_if 中捕获它:

I want to write a templatized function which takes either an array<int, 3> or an int[3]. I'm trying to capture that in an enable_if:

template<typename T>
enable_if_t<is_array_v<T> && extent_v<T> == 3U || !is_array_v<T> && tuple_size<T>::value == 3U> foo(const T& param) {}

不幸的是 int [3 ] tupple_size 未定义,这会导致模板在评估短路之前无法编译。

Unfortunately for an int[3], tupple_size is not defined, which causes the template to fail to compile, before short circuiting is evaluated.

我也尝试过使用有条件的来做到这一点,但这同样存在确保两个选项都对 T有效的问题。 在考虑条件之前。

I have also tried to do this using a conditional but that has the same problem of ensuring both options are valid for T before considering the condition.

我知道我可以通过专门研究来做到这一点。但是代码在函数主体中是完全相同的。我讨厌这样的事实:在实现相同的情况下我会专攻。

I know that I can do this by specializing. But the code is the exact same in the body of the function. I hate the fact that I'm specializing when the implementation is the same.

在评估条件之前,是否有一种方法可以强制短路? / strong>

Is there a way I can force the short circuit before evaluating the conditions?

推荐答案

利用 extent< T> 对于非数组类型为零​​,因此是虚假的,并且 disjunction 从列表中的第一个真实类型派生而出现短路:

Taking advantage of the fact that extent<T> for non-array types is zero and hence falsy, and disjunction derives from the first truthy type in the list with short circuiting:

template<typename T>
enable_if_t<disjunction<extent<T>, tuple_size<T>>::value == 3U> foo(const T& param) {}

这可能太聪明了。请注意,您不能在此处使用 disjunction_v

This is probably too clever. Note that you can't use disjunction_v here.

有条件的应该也可以。诀窍是在选择正确的类型之前不要要求 :: value

conditional should work just fine too. The trick is to not ask for ::value until you've picked the right type:

template<typename T>
enable_if_t<conditional_t<is_array_v<T>, extent<T>, tuple_size<T>>::value == 3U> 
    foo(const T& param) {}

这篇关于enable_if中的短路运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆