Boost logo

Boost :

Subject: Re: [boost] result_of overloaded member function?
From: Daniel Walker (daniel.j.walker_at_[hidden])
Date: 2011-05-04 12:33:30


On Wed, May 4, 2011 at 10:02 AM, Arno Schödl <aschoedl_at_[hidden]> wrote:
> Hello,
>
> is there a way to get the result type of an overloaded member function? Something like:
>
> template< class T, class A >
>
> typename boost::result_of< T::func(A) >::type invoke( T& t, A& a ) {
>
> return t.func(a);
>
> }
>

Not exactly. The template parameters to result_of are types. In your
example, assuming func is the name of an overloaded member function,
T::func is not a type. To call a pointer to member function, assuming
func is a template, you could do the following.

template< class T, class F, class A >
typename boost::result_of< F(A) >::type
invoke_ptr(T t, F f, A a) {
    return (t.*f)(a);
}

struct S0 {
    template<class T>
    T func(T x) { return x; }
};

invoke_ptr(S0(), &S0::func<int>, 1);
invoke_ptr(S0(), &S0::func<float>, 0.1);

It would also work with non-template overloads, but then you need to
specify the type of the member function pointer explicitly.

struct S1 {
    int func(int x) { return x; }
    float func(float x) { return x; }
};

invoke_ptr<S1, int(S1::*)(int), int>(S1(), &S1::func, 1);
invoke_ptr<S1, float(S1::*)(float), float>(S1(), &S1::func, 0.1);

Now, let's assume instead that func is actually a callable object
type; e.g. a functor. Then you could do something like the following,
which is closer to your original example.

template< class T, class A >
typename boost::result_of< typename T::func(A) >::type
invoke(T t, A a) {
    return typename T::func()(a);
}

struct S2 {
    struct func {
        template<class T>
        T operator()(T x) { return x; }
    };
};

invoke(S2(), 1);
invoke(S2(), 0.1);

I compiled these examples on boost trunk with g++ 4.5 with c++0x and
BOOST_RESULT_OF_USE_DECLTYPE defined. But you could use the TR1
result_of protocol to make the last example work in C++03 as well.

Hope that helps!
Daniel Walker


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