有谁能告诉我函数f
的参数类型是什么?
int f(void (*(int,long))(int,long)) {}
在尝试编译一些可变参数模板重代码(我自己的std::thread
包装器)时,我得到了类似的类型...
答案 0 :(得分:31)
声明
int f(void (*(int,long))(int,long)) {}
声明函数f
返回int
并将参数作为参数作为参数,该函数接受int, long
参数并返回指向返回void
的函数的指针参数int, long
。使用typedef作为最里面的函数指针,这变得更具可读性:
typedef void (*fptr)(int, long);
int f(fptr(int, long));
或者使用命名参数
int f(fptr handler(int, long));
这是完全有效的代码,但在编译器输出中看起来很奇怪,因为它使用特殊的语法规则:在函数参数列表中,函数类型声明符声明函数指针参数。也就是说,
int f(fptr handler (int, long)); // is equivalent to
int f(fptr (*handler)(int, long));
...并且您希望编译器使用较低的通用形式。
答案 1 :(得分:13)
这是一个函数,它指向一个以int
和long
为参数的函数,并返回一个以int
和long
为参数的函数,并返回{{1 }}。如果使用尾随返回类型并命名函数可能会更清楚:
void
答案 2 :(得分:3)
在函数声明中
int f(void (*(int,long))(int,long));
使用了模糊形式的函数指针。让我们从基础开始来理解这段代码。
void (*f_ptr)(long);
将f_ptr
声明为指向期望long
参数并且不返回任何内容的函数的指针。
作为函数的参数,此函数指针可以声明为
int f1( void f_ptr(int) );
int f2( void (*f_ptr)(int) );
void f_ptr(int)
和void (*f_ptr)(int)
都与函数参数相同。现在将f_ptr
的返回类型更改为指针void
(void *
)
int f1( void *f_ptr(int) ); // f_ptr is a function pointer that expects an int type and
// returns a pointer to void
int f2( void *(*f_ptr)(int) );
可以删除函数参数的名称,因此上面的声明将变为
int f1( void *(int) );
int f2( void *(*)(int) );
现在您可以对原始函数声明进行反混淆处理
int f( void ( *(int, long) ) (int, long) );
as
int f( void ( *(*)(int, long) ) (int, long) );
您可以为函数指针添加名称
int f( void ( *(*func_ptr)(int, long) ) (int, long) );
因此,func_ptr
是指向需要int
和long
类型参数的函数的指针,并返回指向期望int和long类型参数的函数的指针并返回void
。