c++ - 非可变 lambda 函数 : are copy-captured variables allowed to be const?

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

尝试回复 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 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 bug,报告为 79378 .

关于c++ - 非可变 lambda 函数 : are copy-captured variables allowed to be const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42046021/

相关文章:

c++ - 线程阻止创建窗口

c++ - 将专用插槽连接到 QGraphicsItem 中的 QAction

C++ STL unordered_map,线程安全,其中每个线程只访问它自己分配的键并可以编辑该值

c++ - 从 vector 中检索两个最大值

c++ - 我需要在这里显式调用析构函数吗?

c++ - 对不带参数的可变参数模板函数的调用不明确?

java - 将列表拆分为 3 个子列表 Java 8+

c++ - std::remove_reference 有什么意义

c++ - 我应该怎么做才能初始化结构数组

c# - 使用任意数量的属性初始化新的匿名对象的表达式树