Boost logo

Boost Users :

From: Jean-Pierre Bergamin (james_at_[hidden])
Date: 2008-02-15 03:14:10


Hello

> Gesendet: Donnerstag, 14. Februar 2008 20:44

> > At 8:12 PM +0100 2/14/08, Jean-Pierre Bergamin wrote:

> >Is there a reason why boost::bind does not overload the logical
> >operators || and &&? They definitively would come in more handy to
> >build up complicated logical expressions than using the
> >std::logical_and and std::logical_or function objects.
>
> My guess is that since boost::bind could not replicate the
> behavior of && and ||, the authors decided not to provide them.
>
> The built in && will not evaluate the second argument if the
> first is false.
> Similarly, the built in || will not evalulate the second
> argument if the first is true.
>
> You can write
> if ( p != NULL && p->someField == 3 )
> confident in the knowledge that "p->someField" will not be
> read from if p == NULL.

Thats right. But this is not really a problem of bind, but of the semantics
of the function objects std::logical_and and std::logical_or itself. The
second argument is always evaluated. So IMHO the programmer should be aware
of that anyway when using those logical expressions.
        
        int *p_int_null = NULL;

        bool result = p_int_null != NULL && *p_int_null > 10; // ok

        logical_and<bool> and_op;
        result = and_op(
                p_int_null != NULL,
                *p_int_null > 10
        ); // Oops

Could there be a way to provide a function object safe_logical_and that only
evaluates the second argument if the first one is true?

Regards

Jean-Pierre Bergamin


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