在下面的代码中,我有一个函数成员和一个数据成员,它是一个函数指针。要用于声明或用作模板参数,指向函数成员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;
}
答案 0 :(得分:3)
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;
}
答案 1 :(得分:2)
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)
。