Boost logo

Boost :

Subject: Re: [boost] Does boost help in creating generic function wrappers?
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2010-07-15 16:16:35


AMDG

Andy Venikov wrote:
> Let's say that you have a functor f of type F, where it's
> legal to call it like this:
>
> int n = 5;
> f(n, 10); //compiles fine
> f(n, n); /compiles fine
>
> You seem to suggest I create my own my_wrapper<F> and define an
> operator() with only references:
>
> template <typename Func>
> class my_wrapper
> {
> <snip>
> template <typename T1, typename T2>
> /*deduce ret type*/
> operator() (T1 & in1, T2 & in2);
> };
>
> ... and then wrap it in a forward_adapter:
>
> template <typename Func>
> inline
> forward_adapter<my_wrapper<Func> > wrap(Func const & in);

Yes that's exactly what I mean.

> But now this fails to compile:
>
> wrap(f)(n, 10); //Fails, because 10 is passed as int const &

Since 10 is passed as int const&, T2 should be deduced as const int.
This can't be the problem.

> whereas this used to compile fine:
> f(n, 10);
>
> What am I missing?

Did you include result_of support in your wrapper?

The following compiles for me:

#include <boost/functional/forward_adapter.hpp>
#include <boost/utility/result_of.hpp>

struct func {
    typedef void result_type;
    void operator()(int&, int) const {}
};

template<class F>
class wrapper {
public:
    wrapper(const F& f) : f(f) {}

    template<class Sig>
    struct result;
    template<class This, class Arg1, class Arg2>
    struct result<This(Arg1, Arg2)>
        : boost::result_of<F(Arg1, Arg2)> {};

    template<class T1, class T2>
    typename boost::result_of<F(T1&, T2&)>::type
    operator()(T1& t1, T2& t2) const {
        return f(t1, t2);
    }

private:
    F f;
};

template<class F>
boost::forward_adapter<wrapper<F> > wrap(const F& f) {
    return boost::forward_adapter<wrapper<F> >(wrapper<F>(f));
}

int main() {
    int n = 0;
    func f;
    f(n, 10);
    wrap(f)(n, 10);
}

In Christ,
Steven Watanabe


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