Reputation: 7788
This question is related to this one.
Why doesn't this compile:
int main() {
auto foo = [&]() -> int {foo; return {};}();
(void)(foo);
}
Error:
main.cpp: In lambda function:
main.cpp:3:30: error: use of 'foo' before deduction of 'auto'
auto foo = [&]() -> int {foo; return {};}();
^~~
But casting foo to the resulting type allows compilation:
int main() {
auto foo = [&]() -> int {int(foo); (void)(foo);return {};}();
(void)(foo);
}
Upvotes: 1
Views: 462
Reputation: 137315
Vexing parses again. If something can be a declaration, it is a declaration.
int(foo);
is int (foo);
is int foo;
. Then the foo
in (void)(foo);
refers to the int
.
The first snippet runs into [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.
The type of foo
is needed to determine the type of the expression foo
within the lambda body, but at that point you haven't deduced foo
's type yet, so the program is ill-formed.
Upvotes: 5