0

For some reason this lambda statement doesn't want to compile:

bool DepthFirstSearch = [](Graph *g, bool *ch, stack<int> &S, int v, int w) -> bool
{
 //Here is recursive DFS code
};

with the error: no suitable conversion function from: "lambda[]bool()->bool" to bool exists.

My question is why?

3
  • do you want to store the lambda itself or the result? For the result add a (...); (with the arguments for the call) at the end (after the }) to actually call it. If you want to store it, to call it later, use auto DepthFirstSearch = [](..)...; Commented Nov 19, 2014 at 19:36
  • 6
    Well, you're trying to initialize a bool value with a lambda expression. Did you mean to invoke the lambda at the end of that expression ([](...) -> bool {...}(<arguments go here>))? Commented Nov 19, 2014 at 19:37
  • 2
    A recursive lambda? That's difficult, anyway. Commented Nov 19, 2014 at 19:38

2 Answers 2

1

The type of the lambda isn't bool. You could use auto to make this work

auto DepthFirstSearch = [](Graph *g, bool *ch, stack<int> &S, int v, int w) -> bool { ... }

or use std::function to specify the return type explicitly, but that would be quite cumbersome. See http://en.cppreference.com/w/cpp/utility/functional/function.

Generally it is easier to just use auto, otherwise you'd have to change the type of the variable every time you change the parameters of the lambda.

Sign up to request clarification or add additional context in comments.

1 Comment

I think compilers should refuse lambdas whose initializers reference themselves
1

If you want to make it recursive, then you have to capture the lambda (by ref). To do that, you need to give it a named type:

std::function<bool(Graph*, bool*, stack<int>&, int, int)> DepthFirstSearch = 
    [&](Graph *g, bool *ch, stack<int> &S, int v, int w) {
        // bunch of code here that possibly calls DepthFirstSearch
    };

You can't just do auto DepthFirstSearch = [=](...){...} here because the lambda will need to know the type of DepthFirstSearch in order to capture it - and if you just use auto then the type won't exist until after the lambda-expression is processed, which is too late. Hence the std::function<...>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.