dimanche 5 avril 2020

Why recursive lambda functions are throwing error when used with auto?

I am trying to use recursive lambda functions with auto keyword as below.

#include <iostream>

using namespace std;

int main()
{
    auto func = []()->void{
        static int x = 0;
        cout << x << endl;
        if (x < 5) {
            func();
            x++;
        }
    };

    func();
    return 0;
}

But it is throwing compiler error as below.

main.cpp: In lambda function:
main.cpp:19:13: error: use of ‘func’ before deduction of ‘auto’
             func();
             ^~~~

I understood that we can achieve the same with std::function. But I wanted to know why I am getting error by using 'auto'.

I went through below stack overflow questions.

But I couldn't figure out why auto with lambda is throwing error in this case. Can anyone please let me know why I am getting this error?

Aucun commentaire:

Enregistrer un commentaire