How can I write a lambda expression with two placeholders, one for the callable object, and one for the function argument, such that supplying the callable object first returns a unary function.
In the example below, generate
should be a lambda expression with the first placeholder for the callable object itself, and the second placeholder for the argument. Calling generate(c)
should return a unary function that is only missing the function call argument. In fact, it somehow returns type bool
already, as proved by the static assert.
#include <boost/lambda/bind.hpp>
struct Arg {
};
struct Callable : std::unary_function<Arg, bool> {
bool operator()( Arg const& a ) const { return true; }
};
int main( int argc, const char* argv[] ) {
BOOST_AUTO(generate, boost::lambda::bind(boost::lambda::_1, boost::lambda::protect(boost::lambda::_1)));
Callable c;
BOOST_AUTO(fn, generate(c));
BOOST_STATIC_ASSERT((boost::is_same<BOOST_TYPEOF(fn), bool>::value));
Arg a;
bool b = fn(a);
_ASSERT(b==true);
}
If using Boost.Phoenix the answer would have been a little easier:
#include <boost/phoenix/phoenix.hpp>
struct callable
{
typedef bool result_type;
bool operator()(int) const
{
return true;
}
};
int main()
{
using phx::bind;
using phx::lambda;
using phx::arg_names::_1;
using phx::local_names::_a;
auto generate = lambda(_a = _1)[bind(_a, _1)];
auto fn = generate(callable());
bool b = fn(8);
}
Not that this solution is far more generic than the version posted by the OT. It can be used with any unary function object, no matter what argument, no matter what return type.
The downside, you need to use the current boost trunk ...