非可变lambda函数:是否允许将复制捕获的变量设为const? [英] Non mutable lambda function: are copy-captured variables allowed to be const?

查看:161
本文介绍了非可变lambda函数:是否允许将复制捕获的变量设为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 by decltype(e) is defined as follows: [...] if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named by e.

所以decltype(j)应该是int.这是一个gcc错误,报告为 79378 .

So decltype(j) should be int. This is a gcc bug, reported as 79378.

这篇关于非可变lambda函数:是否允许将复制捕获的变量设为const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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