Using boost to create a lambda function that always returns true

Suppose I have a function that takes some kind of predicate:

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

If I want to call it a predicate that always returns true, I can define a helper function:

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

But is there really a call to this function (possibly using boost :: lambda) without the need to define a separate function?

[Edit: forgot to say: I CANNOT use C ++ 0x]

+5
source share
2 answers

UncleBens commented on this in Sharron's answer, but I think this is actually the best answer, so I steal it (sorry UncleBens). Just use

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

Boost.Lambda, , . , , .

+9

:

#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), (_1, _2 _3), true.

+4

All Articles