Boost logo

Boost :

From: Robert Kawulak (kawulak_at_[hidden])
Date: 2007-08-22 10:39:58


> From: pongba
> I think the design of the interface is an example of taking
> generic programming
> too far. Making the constraints/predicates template
> parameters would have the
> limitations that only state-less functors and compile-time
> constraints could be accepted.

This is not true - have you looked at the constrained class template (for which
bounded_int is only an alias)? It can accept any predicate type (stateful or
not) and you can modify it at runtime.

> This can be unacceptable, if, for instance, my
> predicate is a
> state-ful functor, or if it's a binded function (e.g.
> boost::bind(f, _1, x) ).
> So why not generalize the interface using boost::function, like this:

 [snip]

Why not just use constrained< T, boost::function1<bool, T> >? I attach an
example below.

Best regards,
Robert

struct is_even {
    bool operator () (int i) const
    { return (i % 2) == 0; }
} is_even_fn;

std::binder1st< std::less<int> >
    is_positive_fn(std::less<int>(), 0);

int test_main(int, char*[])
{

    // object constrained by any predicate
    constrained< int, boost::function1<bool, int> >
        c(is_even_fn);
    BOOST_CHECK(c.value() == 0);

    // set to negative value
    THIS_IS_OK_(c = -2);
    BOOST_CHECK(c.value() == -2);

    // cannot change constraint -- the value
    // is not conforming to is_positive_fn
    THIS_FAILS_(change_constraint(c, is_positive_fn));
    BOOST_CHECK(c.value() == -2);

    // set to positive value
    THIS_IS_OK_(c = 2);
    BOOST_CHECK(c.value() == 2);

    // now can change the constraint
    THIS_IS_OK_(change_constraint(c, is_positive_fn));
    BOOST_CHECK(c.value() == 2);

    // now only positive numbers
    THIS_IS_OK_(c = 1);
    BOOST_CHECK(c.value() == 1);
    THIS_FAILS_(c = -2);
    BOOST_CHECK(c.value() == 1);

    return 0;
}

NB: value() call is needed in comparisons, because constrained op == interferes
with function1 op == -- that's the disadvantage of using EBO.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk