C中函数指针的递归声明
我想声明一个返回指向相同类型函数的指针的函数。
我想用它来实现如下所示的状态机:
typedef event_handler_t (*event_handler_t)(event_t*); // compilation error
event_handler_t state2(event_t* e);
event_handler_t state1(event_t* e) {
switch(e->type) {
//...
case SOME_EVENT:
return state2;
//...
}
}
event_handler_t state2(event_t* e) {
switch(e->type) {
//...
case OTHER_EVENT:
return state1;
//...
}
}
//...
event_handler_t event_handler;
//...
event_handler(&e);
//...
我设法使用如下结构来解决编译错误:
typedef struct event_handler {
struct event_handler (*func)(event_t *);
} event_handler_t;
但这使得返回语句更加复杂:
event_handler_t state2(event_t* e) {
{
event_handler_t next_handler = {NULL};
switch(e->type) {
//...
case OTHER_EVENT:
next_handler.func = state1;
break;
//...
}
return next_handler;
}
我想知道是否有更好的方法来创建这样的函数指针C。
I'd like to declare a function that returns a pointer to a function of the same type.
I would like to use it to implement state machines like the one below:
typedef event_handler_t (*event_handler_t)(event_t*); // compilation error
event_handler_t state2(event_t* e);
event_handler_t state1(event_t* e) {
switch(e->type) {
//...
case SOME_EVENT:
return state2;
//...
}
}
event_handler_t state2(event_t* e) {
switch(e->type) {
//...
case OTHER_EVENT:
return state1;
//...
}
}
//...
event_handler_t event_handler;
//...
event_handler(&e);
//...
I manage to work around the compliation error using structures as follows:
typedef struct event_handler {
struct event_handler (*func)(event_t *);
} event_handler_t;
But this makes return statment more complicated:
event_handler_t state2(event_t* e) {
{
event_handler_t next_handler = {NULL};
switch(e->type) {
//...
case OTHER_EVENT:
next_handler.func = state1;
break;
//...
}
return next_handler;
}
I wonder if there is a better way to create such function pointers in c.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 C 中不可能做到这一点:函数不能返回指向自身的指针,因为类型声明递归扩展并且永远不会结束。 有关说明,请参阅此页面:http://www.gotw.ca/gotw/057.htm< /a>
上页描述的解决方法意味着返回
void (*) ()
而不是正确类型的函数指针; 您的解决方法可以说更简洁一些。It's not possible to do this in C: a function can't return a pointer to itself, since the type declaration expands recursively and never ends. See this page for an explanation: http://www.gotw.ca/gotw/057.htm
The workaround described on the above page means returning
void (*) ()
instead of the correctly-typed function pointer; your workaround is arguably a little neater.Herb Sutter 的书 More Exceptional C++,第 32 条对此进行了讨论,其中答案似乎是(对于 C)“不能不使用强制转换”。 对于 C++ 来说,通常可以通过引入类来提供一些额外的间接性。
This is discussed in Herb Sutter's book More Exceptional C++, Item 32, where the answer seems to be (for C) "not without use of casts". For C++ it is possible with the usual introduction of a class to provide some extra indirection.