函数指针数据成员的类型是什么?

What is the type of a function pointer data member?

在下面的代码中,我有一个函数成员和一个函数指针数据成员。为了在声明中使用或作为模板参数,指向函数成员 f 的指针的类型是 int (Test::*)(int);但是指向函数指针数据成员 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;
}
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

您也可以尝试使用模板 typedef 来理清语法(我不确定是否值得):

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;
}
struct Test
{
    int f( int ) { return 0; };
    int (*pf)( int );
};

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

    using PFmem = int (* Test::*)( int );
    PFmem y = &Test::pf;
}

如果您有疑问,可以借助编译器错误消息推断类型:

using PFmem = int; // any type
PFmem y = &Test::pf;

上面的代码导致下面的错误信息:

prog.cpp:13:30: error: cannot convert ‘int (* Test::*)(int)’ to ‘int’ in assignment
     PFmem y = &Test::pf;

从此错误消息我们现在知道所需的类型是 int (* Test::*)(int)