【问题标题】:In C++ is it possible to write a lambda that is a condition i.e. just a condition that evaluates to true or false在 C++ 中是否可以编写一个作为条件的 lambda,即只是一个评估为真或假的条件
【发布时间】:2017-08-24 14:30:08
【问题描述】:

示例(人为):

我写了一个方法,可以接受一个“过滤器”表达式,并返回匹配项的数量:

int getCount(std::function<bool(int, int)> filter)
{
    // Iterate pairs of numbers p,q
    // Count number of pairs where filter(p, q) is true
    // Return count
}

我知道我可以按如下方式调用它:

getCount([](int x, int y) { return x > y; });

但是,由于其目的是编写过滤器“条件”或“表达式”,即非常声明性而非命令性的东西,因此我最好排除“返回”语句。

类似的东西:

getCount([](int x, int y) { x > y; });

getCount([](int x, int y) { x > y });

显然以上是不可能的,但是在 std 或 boost 中是否有任何东西可以让我实现这个意图?

基本上,getCount 方法的用户只需要能够提供过滤条件,而不必说“return”作为命令式语句。

【问题讨论】:

  • 如果没有return,您将无法退货。
  • @NathanOliver 我稍微更新了我的问题。更清楚地说,如果我有一个声明“int a = b + c;”短语“b + c”实际上返回了 b + c 的值,但我们不必说“return”。我只想简单地说“int a = myfunc”;在其他地方我说 myfunc 是“b + c”而不必说“return”。
  • 我们不必在那里说return,因为我们不在函数中。抽象地int a = b + c;int 调用operator+,它进行加法然后返回一个值,然后将该值分配给aoperator+ 仍在做 return。就像我说的,如果不使用return,就不能从函数返回值。
  • return 有什么问题?对我来说,[](int x, int y) { return x &gt; y; }[](int x, int y) { x &gt; y; } 清晰得多
  • 对我来说,使用基本的 stl 函数更有意义,因为它们更灵活并且所有人都易于理解。喜欢size_t count = std::accumulate(v.begin(), v.end(), 0, [=THRESHOLD](size_t n, int x) { return n + (x &gt; THRESHOLD); });

标签: c++ c++11 boost lambda closures


【解决方案1】:

您可以为此使用Boost.Phoenix

using namespace boost::phoenix::placeholders;
getCount(_1 > _2);

_1_2argument placeholders,整个关系表达式形成一个返回比较结果的函数对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    相关资源
    最近更新 更多