简体   繁体   English

C中函数指针的递归声明

[英]Recursive declaration of function pointer in 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. 我想知道是否有更好的方法在c中创建此类函数指针。

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. 用C语言不可能做到这一点:函数不能返回指向自身的指针,因为类型声明是递归扩展的,并且永远不会结束。 See this page for an explanation: http://www.gotw.ca/gotw/057.htm 请参阅此页面以获得说明: http : //www.gotw.ca/gotw/057.htm

The workaround described on the above page means returning void (*) () instead of the correctly-typed function pointer; 上页描述的解决方法是返回void (*) ()而不是正确键入的函数指针; your workaround is arguably a little neater. 您的解决方法可以说有点整洁。

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". 赫伯·萨特(Herb Sutter)的书《 更多例外的C ++》 (Item 32)中对此进行了讨论,答案似乎是(对于C)“不是不使用强制转换”。 For C++ it is possible with the usual introduction of a class to provide some extra indirection. 对于C ++,通常可以通过引入类来提供一些额外的间接访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM