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

后端 未结 4 415
攒了一身酷
攒了一身酷 2020-12-05 13:35

I have compiled following program in GCC using C++14.

#include 
using namespace std;

auto func(int i);

int main() 
{
    auto         


        
4条回答
  •  执笔经年
    2020-12-05 14:25

    In your example, there is really no reason that you could not just move the implementation of the function before main():

    #include 
    using namespace std;  // you should avoid this, too
    
    auto 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 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".

提交回复
热议问题