Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2007-06-08 12:51:13


Boris wrote:
> Hi,
> I have two predicates f1 and f2 and I want to construct the predicate
> f4 = f1 && f2 using boost::bind.
> Unfortunately I observe a strange behaviour of boost::bind I can not
> explain.
>
> struct Test
> {
> int a;
> int b;
> };
>
> Test t = { 1, 2 };
>
> typedef boost::function< bool (Test const&) > Fn;
>
> Fn f1 = bind( &Test::a, _1 ) == 1;
> assert (f1( t )); // Ok
>
> Fn f2 = bind( &Test::b, _1 ) == 3;
> assert (!f2( t )); // ok
>
> Fn f3 = bind(
> std::logical_and< bool >(),
> bind( &Test::a, _1 ) == 1,
> bind( &Test::b, _1 ) == 3 );
> assert (!f3( t )); // Ok
>
> Fn f4 = bind( std::logical_and< bool >(), f1, f2 );
> assert (!f4( t )); // assertion failed
>
> Why does the predicate f4 behave different from f3?

f4( t ) returns f1 && f2, which is true because a function<> in a boolean
context evaluates to true when it's nonempty.

The outer bind cannot see inside f1 and f2 to recognize them as
subexpressions since you've wrapped them in a function<>, so it treats them
as arguments for logical_and. Try

Fn f4 = bind( std::logical_and< bool >(), bind( f1, _1 ), bind( f2, _1 ) );


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net