Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2001-05-02 07:37:05


From: "Rene Jager" <renej_at_[hidden]>

> > I don't see why free functions present a problem; they are always const.
>
> I think there is a difference between the const'ness of a functor and
> the
> const'ness of the underlying function/method; just like in the STL: the
> member
> function can be const or not, the operator () of the function object is
> always
> const having a "const boost::function<int, int> f" IMHO means that
> you're not
> allowed to do "f.clear()", but you can use/call it always since that
> doesn't
> affect the state of the functor; during the construction of a functor it
> should
> not be possible to combine a const object and a non-const member
> function (as in
> mem_fun/const_mem_fun) does this sound reasonible or am I totally of
> track here...

I think that we're talking about different things here. Some examples:

int f(int x); // the function object &f has a const operator()

struct F
{
    int (T::*pmf) (int);
    T * pt;

    int operator()(int x) const // alters neither pt nor pmf, therefore is
const
    {
        return (pt->*pmf)(x);
    }
};

struct G
{
    int x_;

    int operator()(int x) // non-const, alters the state of G
    {
        return x_ += x;
    }
};

A const boost::function<int, int> that holds &f or an instance of F can be
called without problems; if it holds an instance of G (boost::function
conceptually contains the function object, as if it were a member) you
shouldn't be able to call it.

Unfortunately since boost::function binds to the function object's
operator() during construction/assignment time, not during call time, it
won't work with G since its (boost::function's) const operator() cannot be
bound. A dummy const operator() has to be added to G to make it compatible
with boost::function.

I believe that these cases are rare and - correct me if I'm wrong - you're
mainly interested in F-like function objects.

--
Peter Dimov
Multi Media Ltd.

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