尝试回复 another question 时在这里,我发现 GCC 和 clang 使用 lambda 的方式有所不同。
考虑以下代码:
#include <type_traits>
int main() {
int i = 0;
[j = i](){ static_assert(std::is_same<decltype(j), const int>::value, "!"); }();
}
在这种情况下,clang rejects the snippet ,而海湾合作委员会 accepts the code .
另一方面,他们都接受下面的代码(出于明显的原因):
#include <type_traits>
int main() {
int i = 0;
[j = i]()mutable{ static_assert(std::is_same<decltype(j), int>::value, "!"); }();
}
编译器是否允许将 copy 捕获的变量声明为非可变 lambda 的 const?
最佳答案
mutable
在这里并不重要。
在[expr.prim.lambda]中:
An init-capture behaves as if it declares and explicitly captures a variable of the form “
auto
init-capture ;”
来自 [dcl.type.simple]:
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 bug,报告为 79378 .
关于c++ - 非可变 lambda 函数 : are copy-captured variables allowed to be const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42046021/