【问题标题】:Non mutable lambda function: are copy-captured variables allowed to be const?非可变 lambda 函数:是否允许复制捕获的变量为 const?
【发布时间】:2017-06-22 02:38:35
【问题描述】:

在尝试在 SO 上回复 another question 时,我发现 GCC 和 clang 与 lambdas 的工作方式有所不同。

考虑以下代码:

#include <type_traits>

int main() {
    int i = 0;
    [j = i](){ static_assert(std::is_same<decltype(j), const int>::value, "!"); }();
}

在这种情况下,clang rejects the snippet,而 GCC accepts the code

另一方面,他们都接受下面的代码(原因很明显):

#include <type_traits>

int main() {
    int i = 0;
    [j = i]()mutable{ static_assert(std::is_same<decltype(j), int>::value, "!"); }();
}

是否允许编译器将复制捕获的变量声明为非可变 lambda 的 const?

【问题讨论】:

    标签: c++ c++11 lambda language-lawyer


    【解决方案1】:

    mutable 在这里无关紧要。

    在 [expr.prim.lambda] 中:

    init-capture 的行为就好像它声明并显式捕获了“autoinit-capture;”形式的变量

    从[dcl.type.simple]:

    对于表达式edecltype(e) 表示的类型定义如下: [...] 如果e 是无括号的id-expression 或无括号的类成员访问(5.2.5),decltype(e)e命名的实体的类型。

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

    【讨论】:

    • 有趣。我将向 GCC 打开另一个错误。谢谢。
    • @skypjack 刚刚做了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多