|
Boost Users : |
From: dizzy (dizzy_at_[hidden])
Date: 2008-02-15 10:19:20
On Friday 15 February 2008 17:07:21 Michael Fawcett wrote:
> On Fri, Feb 15, 2008 at 3:14 AM, Jean-Pierre Bergamin <james_at_[hidden]>
wrote:
> > 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?
>
> I've written something like that before as:
>
> // warning, code typed in e-mail
> template <typename F0, typename F2>
> struct and_
> {
> F0 first;
> F1 second;
>
> and_(F0 f0, F1, f1) : first(f0), second(f1) { }
>
> bool operator()() const
> {
> return first() && second();
> }
> };
>
> but if you needed function arguments that weren't available to be
> bound at and_ construction time you'd have to do some more trickery.
> This would also scale well using variadic templates.
I don't understand how this code does not evaluate the second argument if the
first one isn't true (the previous poster explicitely requested that). When
you construct the above functor evaluation of the expression given for "f1"
argument will happen which may run into UB, ie the classical "if (p &&
p->flag)" idiom is broken (and you seem to recognize that... no idea then
what you ment with the code).
The only way to do it as I can think of it is using some kind of "lazy
evaluation" technique. In order to still use similar syntax (again taking
the "if (p && p->flag)") one could do something with operator overloading
(like boost.lambda overloads as many operators as it can to construct the
lambda functors using familiar syntax). Basically something like "evaluate
expression p->flag later", but the problem is you won't be able to say "flag"
as an expression, you will probably in such a case have to give "p" and a
pointer to a member value (for "flag") and have the functor "lazy evaluate"
using p->*flagptr which is not all the time (because of overloading ->
or ->*) the same as p->flag (if flagptr is the member pointer of flag).
I am also interested to see other/better solutions.
-- Mihai RUSU Email: dizzy_at_[hidden] "Linux is obsolete" -- AST
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