代码之家  ›  专栏  ›  技术社区  ›  stusmith

使用boost创建始终返回true的lambda函数

  •  5
  • stusmith  · 技术社区  · 15 年前

    假设我有一个函数,它采用某种形式的谓词:

    void Foo( boost::function<bool(int,int,int)> predicate );
    

    如果我想用一个总是返回true的谓词来调用它,我可以定义一个助手函数:

    bool AlwaysTrue( int, int, int ) { return true; }
    ...
    Foo( boost::bind( AlwaysTrue ) );
    

    但是是否有必要在不定义单独函数的情况下调用这个函数(可能使用boost::lambda)?

    编辑:忘了说:我不能使用C++0x]

    2 回复  |  直到 10 年前
        1
  •  9
  •   SCFrench    15 年前

    叔伯在沙伦的回答中对此进行了评论,但我认为这实际上是最好的答案,所以我正在窃取它(对不起,叔伯)。简单使用

    Foo(boost::lambda::constant(true));
    

    如上所述 the documentation for Boost.Lambda ,只有函数的最小arity为零,最大arity为无限制。所以传递给函数的任何输入都将被忽略。

        2
  •  4
  •   Scharron    15 年前

    下面是一个简单的例子:

    #include <boost/function.hpp>
    #include <boost/lambda/lambda.hpp>
    #include <iostream>
    
    void Foo( boost::function<bool(int,int,int)> predicate )
    {
      std::cout << predicate(0, 0, 0) << std::endl;
    }
    
    int main()
    {
      using namespace boost::lambda;
      Foo(true || (_1 + _2 + _3));
    }
    

    诀窍在于 true || (_1 + _2 + _3) 在这里你用3个参数创建一个Boost lambda( _1 , _2 _3 )始终返回 true .