Why does C++17 if statement with initializer not work as expected?
Asked Answered
O

1

10
struct A
{
    auto g1()
    {
        return true;
    }

    void f()
    {
        if (auto b = g1(); b) // ok
        {
            return;
        }

        if (auto b = g2(); b) // error: use of 'auto A::g2()' before deduction of 'auto'
        {
            return;
        }
    }    
    
    auto g2()
    {
        return true;
    }
};

Why does C++17 if statement with initializer not work as expected?

Obstacle answered 6/5, 2021 at 12:21 Comment(5)
You can simplify your demo to struct A { void f() { g2(); } auto g2() { } };. The if-initializer is a red herring.Retool
I'm guessing here but is this caused by the same reason why we can call later declared functions inside a class? The body of a member function is checked after the class itself is checked. Because of that, auto deduction hasn't kicked in yet, because the function body isn't parsed yet. If you put g2 above f it works fine.Implicative
@OP, I noticed you tagged this with the standards tag. Does that mean you are looking for text from the standard to back up any answer that is posted?Joey
@NathanOliver, Yes. That's just what I mean.Obstacle
Okay. I updated to use the language-lawyer tagJoey
G
8

Because the standard says so (quote from latest draft):

[dcl.spec.auto.general]

If a variable or function with an undeduced placeholder type is named by an expression ([basic.def.odr]), the program is ill-formed. Once a non-discarded return statement has been seen in a function, however, the return type deduced from that statement can be used in the rest of the function, including in other return statements.

[Example 4:

auto n = n;                     // error: n's initializer refers to n
auto f();
void g() { &f; }                // error: f's return type is unknown

To add a little bit of clarification, the "declaration" of g2 is "seen" because the definition of g1 is in the complete-class context. But that does not extend to having seen the definition of g2.

Glauconite answered 6/5, 2021 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.