How do I deduce auto before a function is called?

烈酒焚心 提交于 2019-12-10 12:32:20

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/20749951/how-do-i-deduce-auto-before-a-function-is-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!