xinaiz
xinaiz

Reputation: 7788

Can't use captured variable before deduction of auto

This question is related to this one.

Why doesn't this compile:

int main() {
    auto foo = [&]() -> int {foo; return {};}();
    (void)(foo);
}

LIVE on Coliru

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);
}

LIVE on Coliru

Upvotes: 1

Views: 462

Answers (1)

T.C.
T.C.

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

Related Questions