这个问题与这个one有关.
为什么不编译:
int main() {
auto foo = [&]() -> int {foo; return {};}();
(void)(foo);
}
错误:
main.cpp: In lambda function:
main.cpp:3:30: error: use of 'foo' before deduction of 'auto'
auto foo = [&]() -> int {foo; return {};}();
^~~
但是将 foo 转换为结果类型允许编译:
int main() {
auto foo = [&]() -> int {int(foo); (void)(foo);return {};}();
(void)(foo);
}
最佳答案
烦人的再次解析。如果某物可以是声明,它就是声明。
int(foo);
是 int (foo);
是 int foo;
。那么(void)(foo);
中的foo
就是指int
。
第一个片段遇到了 [dcl.spec.auto]/10 :
If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed.
需要 foo
的类型来确定 lambda 体内表达式 foo
的类型,但此时您还没有推导出 foo
的类型,所以程序格式错误。
关于c++ - 在扣除自动之前不能使用捕获的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43054365/