非可变lambda函数:是否允许将复制捕获的变量设为const? [英] Non mutable lambda function: are copy-captured variables allowed to be const?
问题描述
在尝试在此处回复另一个问题时,我发现GCC和clang与lambda配合使用的方式有所不同.
While trying to reply to another question here on SO, I found a difference in how GCC and clang work with lambdas.
考虑以下代码:
#include <type_traits>
int main() {
int i = 0;
[j = i](){ static_assert(std::is_same<decltype(j), const int>::value, "!"); }();
}
在这种情况下,clang 拒绝代码段,而GCC
In this case, clang rejects the snippet, while GCC accepts the code.
另一方面,他们两个都接受下面的代码(出于明显的原因):
On the other side, both of them accept the code below (for obvious reasons):
#include <type_traits>
int main() {
int i = 0;
[j = i]()mutable{ static_assert(std::is_same<decltype(j), int>::value, "!"); }();
}
编译器是否允许将由复制捕获的变量声明为非可变lambda的const?
Are compilers allowed to declare variables captured by copy as const for non-mutable lambdas?
推荐答案
mutable
在这里无关紧要.
在[expr.prim.lambda]中:
In [expr.prim.lambda]:
init-capture 的行为就像声明并显式捕获"
auto
init-capture;"形式的变量一样.
An init-capture behaves as if it declares and explicitly captures a variable of the form "
auto
init-capture ;"
然后从[dcl.type.simple]:
And from [dcl.type.simple]:
对于表达式
e
,由decltype(e)
表示的类型定义如下:[...]如果e
是未括号的 id-expression 或未括号的类成员访问(5.2.5),decltype(e)
是由e
命名的实体的类型.
For an expression
e
, the type denoted bydecltype(e)
is defined as follows: [...] ife
is an unparenthesized id-expression or an unparenthesized class member access (5.2.5),decltype(e)
is the type of the entity named bye
.
所以decltype(j)
应该是int
.这是一个gcc错误,报告为 79378 .
So decltype(j)
should be int
. This is a gcc bug, reported as 79378.
这篇关于非可变lambda函数:是否允许将复制捕获的变量设为const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!