C++ 不可变lambda函数:复制捕获的变量是否允许为常量?

C++ 不可变lambda函数:复制捕获的变量是否允许为常量?,c++,c++11,lambda,language-lawyer,C++,C++11,Lambda,Language Lawyer,当我试图回答这里的问题时,我发现GCC和clang与lambdas的工作方式有所不同 考虑以下代码: #include <type_traits> int main() { int i = 0; [j = i](){ static_assert(std::is_same<decltype(j), const int>::value, "!"); }(); } #包括 int main(){ int i=0; [j=i](){static_assert(

当我试图回答这里的问题时,我发现GCC和clang与lambdas的工作方式有所不同

考虑以下代码:

#include <type_traits>

int main() {
    int i = 0;
    [j = i](){ static_assert(std::is_same<decltype(j), const int>::value, "!"); }();
}
#包括
int main(){
int i=0;
[j=i](){static_assert(std::is_same::value,!”;}();
}
在这种情况下,叮当声,而GCC

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

#包括
int main(){
int i=0;
[j=i]()可变的{static_断言(std::is_same::value,!”;}();
}

是否允许编译器将copy捕获的变量声明为不可变lambda的常量?

可变
在这里并不重要

在[expr.prim.lambda]中:

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

和来自[dcl.type.simple]:

对于表达式
e
,由
decltype(e)
表示的类型定义如下:[…]如果
e
是一个未授权的id表达式或未授权的类成员访问(5.2.5),
decltype(e)
是由
e
命名的实体的类型


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

有趣。我将向GCC打开另一个bug。“谢谢你。”斯凯普杰克刚刚说了。
#include <type_traits>

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