我可以在lambda中使用constexpr值而不捕获它吗? [英] Can I use a constexpr value in a lambda without capturing it?
问题描述
我想在lambda中使用constexpr值。阅读
请特别注意突出显示的示例。 f(x)
不必捕获 x
,因为它没有被滥用(选择过载分辨率) object参数的重载)。同样的论点也适用于您的代码-[basic.def.odr] / 3:
变量
x
其名称显示为可能评估的表达式
ex
由ex
除非将左值到右值转换
(4.1)应用于x
会产生一个常数表达式(5.20)不会调用
的任何非平凡函数…
当然可以满足此要求。
...并且,如果
x
是对象,则ex
是
的元素,是表达式e
的潜在结果的集合,其中
的左值是右值转换(4.1)应用于e
,或者e
是被丢弃的
,值表达式(第5条)。
i
是其潜在结果集按照[basic.def.odr] /(2.1),而ltr转换i
因此,我们已经证明(12.1)不适用-和( 12.2)显然也不是-Clang拒绝您的代码段是错误的。
I would want to use a constexpr value in a lambda. Reading the answer to Using lambda captured constexpr value as an array dimension, I assumed the following should work:
#include<array>
int main()
{
constexpr int i = 0;
auto f = []{
std::array<int, i> a;
};
return 0;
}
However, Clang 3.8 (with std=c++14) complains that
variable 'i' cannot be implicitly captured in a lambda with no capture-default specified
Should this be considered a bug in clang 3.8?
BTW:
The above code does compile with gcc 4.9.2. If I change the lambda expresion to capture explicitly:
...
auto f = [i]{
...
clang 3.8 compiles it, but gcc 4.9.2 fails:
error: the value of ‘i’ is not usable in a constant expression ...
Should this be considered a bug in clang 3.8?
Yep. A capture is only needed if [expr.prim.lambda]/12 mandates so:
Note in particular the highlighted example. f(x)
does not necessitate x
to be captured, because it isn't odr-used (overload resolution selects the overload with the object parameter). The same argumentation applies to your code - [basic.def.odr]/3:
A variable
x
whose name appears as a potentially-evaluated expressionex
is odr-used byex
unless applying the lvalue-to-rvalue conversion (4.1) tox
yields a constant expression (5.20) that does not invoke any non-trivial functions…
This requirement is certainly met.
…and, if
x
is an object,ex
is an element of the set of potential results of an expressione
, where either the lvalue-to-rvalue conversion (4.1) is applied toe
, ore
is a discarded-value expression (Clause 5).
i
is its set of potential results as per [basic.def.odr]/(2.1), and the l-t-r conversion is indeed immediately applied as its passed to a non-type template parameter of object type.
Hence, as we have shown that (12.1) isn't applicable - and (12.2) clearly isn't, either - Clang is wrong in rejecting your snippet.
这篇关于我可以在lambda中使用constexpr值而不捕获它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!