In your example, there is really no reason that you could not just move the implementation of the function before main()
:
#include <iostream>using namespace std; // you should avoid this, tooauto func(int i){ if (i == 1) return i; else return func(i-1) + i;}int main(){ auto ret = func(5); return 0;}
Otherwise you just can't use the auto keyword. In particular, you can't use auto in a recursive function which does not return anything. You have to use void
. And that applies to lambda functions. For example:
int main(){ auto f = [](int i) { // ... do something with `i` ... if(i > 0) { f(i - 1); // <-- same error here } } auto ret(func(5)); return 0;}
The call f(i - 1)
has a problem. To fix it you have to replace the auto
by the actual type:
int main(){ typedef std::function<void(int)> func_t; func_t f = [](int i) { ...
If you really want a function which support varying return types you want to use a template anyway, not auto
. This is really only to help you with less typing, not so much as a way to allow "any type".