我今天尝试做类似的事情。我很惊讶它没有编译。
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;
};
它表示 Test
类型在范围内不完整。然而 lambda 的手写版本确实有效。这样做的技术原因是什么?是标准中的疏忽,还是有特定的措辞使 Test
在 lambda 中不完整?
最佳答案
这是我能找到的:
§5.1.2 Lambda expressions [expr.prim.lambda]
[...] [ Note: Names referenced in the lambda-declarator are looked up in the context in which the lambda-expression appears. —end note ]
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.
如果我没有误读标准,这意味着参数以及正文中的 Test
和 self
都会在 lambda 的上下文中查看/考虑,这是 Test
不完整的类范围。
至于为什么允许嵌套类:
§9.2 Class members [class.mem]
- 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/