c++ - 为什么静态 lambda 成员的封闭类型不完整?

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

我今天尝试做类似的事情。我很惊讶它没有编译。

struct Test {
//  v----- Remove me to compile
    //  /*
    static constexpr auto get_test1 = [](Test const& self) {
        return self.test; // error, Test is incomplete
    };
    // */

    // Handwritten version of the lambda
    struct {
        constexpr auto operator() (Test const& self) const {
            return self.test; // ok
        }
    }
    static constexpr get_test2{};

    int test;
};

Live example

它表示 Test 类型在范围内不完整。然而 lambda 的手写版本确实有效。这样做的技术原因是什么?是标准中的疏忽,还是有特定的措辞使 Test 在 lambda 中不完整?

最佳答案

这是我能找到的:

§5.1.2 Lambda expressions [expr.prim.lambda]

  1. [...] [ Note: Names referenced in the lambda-declarator are looked up in the context in which the lambda-expression appears. —end note ]

  2. The lambda-expression’s compound-statement yields the function-body (8.4) of the function call operator, but for purposes of name lookup (3.4), [...] the compound-statement is considered in the context of the lambda-expression.

如果我没有误读标准,这意味着参数以及正文中的 Testself 都会在 lambda 的上下文中查看/考虑,这是 Test 不完整的类范围。

至于为什么允许嵌套类:

§9.2 Class members [class.mem]

  1. A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the classspecifier . Within the class member-specification, the class is regarded as complete within function bodies, default arguments, using-declarations introducing inheriting constructors (12.9), exception-specification s, and brace-or-equal-initializer s for non-static data members (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.

关于c++ - 为什么静态 lambda 成员的封闭类型不完整?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49289691/

相关文章:

c++ - 如何在链接存档文件时将库版本信息添加到 elf 文件,并且所有存档文件都有其版本信息?

C++ lambda 捕获 - 哪个被捕获?

c++ - 与 using 声明冲突的重载

c - POSIX 在 stdint.h 中的 "two' s 补码表示是什么意思?

c++ - 如何在 C++ 中使用 libcurl 发送和接收 POST 请求?

c++ - 调试 OpenCL 内核的最佳方式

c++ - 2 个值的容器(对于每个 float 一个可操作的整数)

node.js - 使用 AWS 的动态网站

java - 为什么 Java 中的 `orElseThrow()` 方法将 `Supplier` 作为参数而不是 `Exception` ?

c++ - 函数参数的 MSVC 和 constexpr?