tags:

views:

105

answers:

2

Suppose I have a function which takes some form of predicate:

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

If I want to call it with 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 anyway to call this function (possibly using boost::lambda) without having to define a separate function?

[Edit: forgot to say: I CAN'T use C++0x]

+4  A: 

Here is a quick example :

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

The trick is in true || (_1 + _2 + _3) where you are creating a boost lambda with 3 arguments (_1, _2 and _3), always returning true.

Scharron
I don't know enough about lambda to actually answer, but I assume that "Foo(true || _3)" would also work
stefaanv
It appears you can even do just: `Foo(constant(true));` This is nullary, but this is only the minimum arity of the functor.
UncleBens
+4  A: 

UncleBens commented on this in Scharron's answer, but I think it is actually the best answer so I'm stealing it (sorry UncleBens). Simply use

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

As described in the documentation for Boost.Lambda, only the minimum arity of the functor is zero, the maximum arity is unlimited. So any inputs passed to the functor will simply be ignored.

SCFrench
I've been having a look myself and came across boost::lambda::identity... anyone know the difference? They both seem to work.
stusmith
identity appears to be an undocumented template class, used in the implementation of constant (and boost::lambda::var). Much like std::mem_fun_t is the class that the helper function std::mem_fun creates and returns, except that mem_fun_t is documented and identity is not. Given that, I'd recommend using var and constant instead.
SCFrench