views:

88

answers:

1

Given the following code which I can't get to compile.

    template < typename OT, typename KT, KT (OT::* KM)() const >
    class X
    {
    public:
        KT mfn( const OT & obj )
        {
            return obj.*(KM)();    // Error here.
        }
    };

    class O
    {
    public:
        int func() const
        {
            return 3;
        }
    };

    int main( int c, char *v[] )
    {
        int a = 100;

        X<  O, int, &O::func > x;

        O o;

        std::cout << x.mfn( o ) << std::endl;
}

I get the folling error message

error: must use '.*' or '->*' to call pointer-to-member function in '&O::func (...)'

I thought I was using .* but I've obviously got something wrong.

How do I call the member function ?

I've tried

return obj.*(template KM)();
return obj.*template (KM)();
return obj.template *(KM)();

None of which worked.

+5  A: 

The correct syntax is

return (obj.*KM)();
Gareth Stockwell
Thanks Gareth.. I am officially a muppet :) That was about the only one I didn't try.
ScaryAardvark
For a reminder, think of the pointer to function not being complete without the object it's going to act on (`this` is needed after all). If you take a functor point of view, it makes more sense, at least that's how I try to remember the syntax... and when I cannot I just google `C++ pointer to function` and here is the link that always come right away: http://www.newty.de/fpt/fpt.html :)
Matthieu M.