Use of 'auto func(int)' before deduction of 'auto' in C++14

This is [dcl.spec.auto/11]:

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. 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:

auto n = n;                     // error, n's type is unknown
auto f();
void g() { &f; }                // error, f's return type is unknown
auto sum(int i) {
  if (i == 1)
    return i;                   // sum's return type is int
  else
    return sum(i-1)+i;          // OK, sum's return type has been deduced
}

 — end example ]

To translate this into English: the compiler needs to know the return type before you can use the function. In case of auto used like this, this is typically achieved by moving the definition before the point of use. If you don't actually need to use return type deduction, you can keep the definition after the use if you provide a signature, including the return type, in the declaration.


Clang has a much better error message for that one:

main.cpp:8:16: error: function 'func' with deduced return type cannot be used before it is defined
    auto ret = func(5);
               ^

I guess that's self-explanatory.


When auto is used as the return type in a function declaration that does not use the trailing return type syntax, the keyword auto indicates that the return type will be deduced from the operand of its return statement. That means the deduction can't be performed until the definition of the function func(), but before that it has been used in main().

You could move the definition before main(), or use trailing return type syntax to specify the return type on the declaration.