[英]Pointer to function returning function pointer
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
:
typedef void (*func)();
typedef func (*funky_func)();
funky_func ptr;
I tried the following 我尝试了以下内容
(void (*)()) (*ptr)();
but it gives an "undeclared identifier" -error for ptr
(probably due to completely different parsing). 但它为
ptr
提供了一个“未声明的标识符” - 错误(可能是由于完全不同的解析)。 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. 由于不熟悉解析C ++的复杂性,我想知道这是否可行,如果是,那该怎么做。
(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.) (为了好奇,请考虑这是一个完全人为的场景,没有任何实际原因。我完全清楚,在实践中,如果使用函数指针,那么
typedef
就是这里的方法。)
You can have a look at the declaration of signal()
which is a function taking a void(*)()
and returning one of those. 你可以看看
signal()
的声明,它是一个带有void(*)()
并返回其中一个的函数。 The variable ptr
can be declared like this: 变量
ptr
可以这样声明:
void (*(*ptr)())()
The notation is a bit awkward and clearly inside out. 符号有点尴尬,显而易见。 It may be easier to use trailing return types:
使用尾随返回类型可能更容易:
auto (*ptr)() -> void (*)()
... or, of course, use trailing return types all the way through: ...或者,当然,一直使用尾随返回类型:
auto (*ptr)() -> auto (*)() -> void
The general rule of C (and C++) declarations is: if you type the declaration as an expression, it will have the declaration's type. C(和C ++)声明的一般规则是:如果您将声明类型化为表达式,它将具有声明的类型。
So, you want a pointer to function which returns pointer to function returning void. 所以,你想要一个指向函数的指针,它返回指向函数返回void的指针。
Let's say we have such a pointer, ptr
. 假设我们有一个指针,
ptr
。 How to get void
out of it? 如何获得
void
出来的吗?
Dereference ptr
, getting a function returning pointer to function returning void: *ptr
取消引用
ptr
,获取函数返回指向函数的指针返回void: *ptr
Call the function, getting a pointer to function returning void: (*ptr)()
调用函数,获取函数返回void的指针:
(*ptr)()
Dereference that pointer, getting a function returning void: *(*ptr)()
取消引用指针,得到函数返回void:
*(*ptr)()
Call that function, getting void: (*(*ptr)())()
调用该函数,得到无效:
(*(*ptr)())()
Now just turn this into a declaration: 现在把它变成一个声明:
void (*(*ptr)())();
PS I know other have answered in the meantime (and I've upvoted). PS我知道其他人在此期间已经回答了(我已经投了赞成票)。 But I wanted to show the generic process to arrive at the declaration form.
但我想展示通用流程以获得申报表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.