Search code examples
c++function-pointerspointer-to-member

What is the type of a function pointer data member?


In the following code, I have a function member and a data member which is a function pointer. For use in a declaration or as a template parameter, the type of a pointer to the function member f is int (Test::*)(int); but what is the analogous type of a pointer to the function pointer data member pf?

struct Test
{
    int f( int ) { return 0; };
    int (*pf)( int );
};

int main()
{
    using Fmem = int (Test::*)( int );
    Fmem   x = &Test::f;

    // using PFmem = ??;
    // PFmem  y = &Test::pf;
}

Solution

  • using PFmem = int (*Test::*)( int );
    //                        ^ a pointer ...
    //                  ^^^^^^ to a member of Test ...
    //                 ^ which is a pointer ...
    //                          ^     ^ to a function ...
    //                            ^^^ taking an int ...
    //            ^^^ returning an int
    

    You can also try to untangle the syntax with template typedefs (I'm not sure if it's worth it):

    struct Test
    {
        int f( int ) { return 0; };
        int (*pf)( int );
    };
    
    template<typename T>                using pointer_to           = T *;
    template<class C, typename T>       using pointer_to_member_of = T C::*;
    template<typename R, typename ...A> using function             = R (A ...);
    
    int main()
    {
        using Fmem = int (Test::*)( int );
        Fmem   x = &Test::f;
    
        using PFmem = int (*Test::*)( int );
        PFmem  y = &Test::pf;
    
        pointer_to_member_of<Test, function<int, int>>
            x1 = &Test::f;
        pointer_to_member_of<Test, pointer_to<function<int, int>>>
            y2 = &Test::pf;
    }