【问题标题】:Recursive boolean lambda C++递归布尔 lambda C++
【发布时间】:2015-01-17 11:26:18
【问题描述】:

由于某种原因,这个 lambda 语句不想编译:

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

出现错误:no suitable conversion function from: "lambda[]bool()-&gt;bool" to bool exists

我的问题是为什么?

【问题讨论】:

  • 您要存储 lambda 本身还是结果?对于结果,在末尾(} 之后)添加一个(...);(带有调用的参数)来实际调用它。如果你想存储它,以后调用它,使用auto DepthFirstSearch = [](..)...;
  • 好吧,您正在尝试使用 lambda 表达式初始化 bool 值。您的意思是在该表达式的末尾调用 lambda ([](...) -&gt; bool {...}(&lt;arguments go here&gt;))?
  • 递归 lambda?无论如何,这很困难。

标签: c++ c++11 recursion lambda boolean


【解决方案1】:

如果你想让它递归,那么你必须捕获 lambda(通过 ref)。为此,您需要给它一个命名类型:

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
    };

您不能在这里只使用auto DepthFirstSearch = [=](...){...},因为 lambda 需要知道 DepthFirstSearch 的类型才能捕获它 - 如果您只使用 auto,那么该类型在处理 lambda 表达式,为时已晚。因此std::function&lt;...&gt;

【讨论】:

    【解决方案2】:

    lambda 的类型不是bool。您可以使用auto 来完成这项工作

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

    或使用std::function 明确指定返回类型,但这会很麻烦。见http://en.cppreference.com/w/cpp/utility/functional/function

    通常只使用 auto 会更容易,否则每次更改 lambda 的参数时都必须更改变量的类型。

    【讨论】:

    • 我认为编译器应该拒绝初始化器引用自己的 lambdas
    猜你喜欢
    • 2018-06-27
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 2011-12-12
    • 1970-01-01
    • 2013-10-08
    • 2018-09-25
    相关资源
    最近更新 更多