How do I deduce auto before a function is called?

7.6k views Asked by At

while experimenting with function return type deduction

auto func();

int main() { func(); }

auto func() { return 0; }

error: use of ‘auto func()’ before deduction of ‘auto’

Is there a way to use this feature without needing to specify the definition before the call? With a large call tree, it becomes complicated to re-arrange functions so that their definition is seen before all of the places they are called. Surely an evaluation could be held off until a particular function definition was found and auto could then be deduced.

4

There are 4 answers

0
Yakk - Adam Nevraumont On BEST ANSWER

No, there is not.

Even ignoring the practical problems (requiring multi-pass compilation, ease of making undecidable return types via mutually recursive type definitions, difficulty in isolating source of compilation errors when everything resolves, etc), and the design issues (that forward declaration is nearly useless), C++11 was designed with ease of implementation in mind. Things that made it harder to write a compiler needed strong justification.

The myriad restrictions on auto mean that it was really easy to slide it into existing compilers: it is among the most supported C++11 features in my experience. C++14 relaxes many of the restrictions, but does not go nearly as far as you describe. Each relaxation requires justification and confidence that it will be worth the cost to compiler writers to implement.

I would not even want that feature at this time, as I like the signatures of my functions to be deducible at the point I call them, at the very least.

0
Peter Alexander On

No, this simply isn't possible with C++'s compilation model. Remember that the definition of func may appear in a different file, or even inside a library somewhere. The return type must be known if you are going to use it.

0
Dietmar Kühl On

The relevant paper is N3638 which prohibits use of functions declared with an auto return prior to knowning the return type. The paper actually makes a point, however, that as soon as the return type could be deduced from the function body it can also be called! Thus, a function with an auto return can actually be recursive.

0
David Rodríguez - dribeas On

I would avoid automatic deduction of the return type in functions in as much as you can. While it might appear to be a nice feature that eases the need to actually figure out the type, it is not a simple feature to use, and it has limitations (the return type cannot be used in an SFINAE context, it requires the instantiation of the function...)

The answer to your question is that the compiler cannot infer the type without seeing the definition, and the processing is always done in a top-down approach.