Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deduce auto before a function is called?

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.

like image 510
Trevor Hickey Avatar asked Dec 23 '13 19:12

Trevor Hickey


People also ask

Can you declare an auto variable in C++?

The auto keyword is a simple way to declare a variable that has a complicated type. For example, you can use auto to declare a variable where the initialization expression involves templates, pointers to functions, or pointers to members.

What is the Auto function in C++?

The auto keyword in C++ automatically detects and assigns a data type to the variable with which it is used. The compiler analyses the variable's data type by looking at its initialization. It is necessary to initialize the variable when declaring it using the auto keyword.

Which is the default return type specifier in C Plus Plus?

I have recently read that the default return type for all functions in C++ is int .


2 Answers

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.

like image 170
Yakk - Adam Nevraumont Avatar answered Oct 20 '22 12:10

Yakk - Adam Nevraumont


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.

like image 39
Peter Alexander Avatar answered Oct 20 '22 11:10

Peter Alexander