指向函数的指针,返回函数指针 [英] Pointer to function returning function pointer
问题描述
我想声明一个 pointer类型的变量,该变量指向函数,返回指向函数的指针.本质上,以下代码可以执行以下操作,但是没有任何 typedef
s:
I would like to declare a variable of type pointer to function returning pointer to function. Essentially what the following does, but without any typedef
s:
typedef void (*func)();
typedef func (*funky_func)();
funky_func ptr;
我尝试了以下
(void (*)()) (*ptr)();
,但是它为 ptr
提供了未声明的标识符" -错误(可能是由于完全不同的解析).我不了解解析C ++的复杂性,所以我想知道这是否可能,如果可以,怎么做.
but it gives an "undeclared identifier"-error for ptr
(probably due to completely different parsing). Being not that well-versed in the intricacies of parsing C++, I'd like to know if this is even possible and if yes, how to do it.
(出于好奇,请考虑将其完全人为化,没有任何实际原因.我完全意识到,在实践中,如果在以下位置使用函数指针,则 typedef
s是解决问题的方法全部.)
(Please consider this an entirely artificial scenario for the sake of curiosity, without any practical reason. I am perfectly aware that in practice typedef
s are the way to go here, if using function pointers at all.)
推荐答案
C(和C ++)声明的一般规则是:如果将声明键入为表达式,它将具有声明的类型.
The general rule of C (and C++) declarations is: if you type the declaration as an expression, it will have the declaration's type.
因此,您想要一个指向函数的指针,该指针将返回指向返回void的函数的指针.
So, you want a pointer to function which returns pointer to function returning void.
比方说,我们有这样的指针 ptr
.如何从中获取 void
?
Let's say we have such a pointer, ptr
. How to get void
out of it?
-
取消引用
ptr
,获得一个函数,该函数返回指向返回void的函数的指针:* ptr
Dereference
ptr
, getting a function returning pointer to function returning void:*ptr
调用该函数,获得指向返回空值的函数的指针:(* ptr)()
Call the function, getting a pointer to function returning void: (*ptr)()
取消引用该指针,获取返回void的函数: *(* ptr)()
Dereference that pointer, getting a function returning void: *(*ptr)()
调用该函数,结果无效:(*(* ptr)())()
Call that function, getting void: (*(*ptr)())()
现在将其转换为声明:
void (*(*ptr)())();
P.S.我知道其他人在此期间已回答(并且我已投票赞成).但是我想展示到达申报表的通用过程.
P.S. I know other have answered in the meantime (and I've upvoted). But I wanted to show the generic process to arrive at the declaration form.
这篇关于指向函数的指针,返回函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!