无法解析的自引用
这是不可能直接实现的。如果您尝试定义一个函数指针类型,其中函数的返回类型是其自身的类型,您将遇到未解析的自引用,并且需要无限递归来解析。
typedef funcType (*funcType)(void);
返回一个struct
您可以改为声明该函数返回一个结构,并且该结构可以包含指向此类函数的指针。
struct func {
struct func (*func) (void);
};
struct func foo (void);
struct func bar (void);
struct func foo (void) { return (struct func){ bar }; }
struct func bar (void) { return (struct func){ foo }; }
...
struct func funcPtr = { foo };
funcPtr = funcPtr.func();
返回不同的函数指针类型
如果您更喜欢严格使用指针,则需要定义返回不同函数指针类型的函数。因此,在调用之前,调用的结果必须转换回正确的指针类型。
typedef void (*funcPtrType)(void);
typedef funcPtrType funcType(void);
funcType foo;
funcType bar;
funcPtrType foo (void) { return (funcPtrType)bar; }
funcPtrType bar (void) { return (funcPtrType)foo; }
...
funcType *p = foo;
p = (funcType *)p();
Return an index†
您可以定义函数来返回表示应调用函数的表的索引。
enum funcEnum { fooEnum, barEnum };
typedef enum funcEnum (*funcType)(void);
enum funcEnum foo (void) { return barEnum; }
enum funcEnum bar (void) { return fooEnum; }
funcType funcTable[] = { [fooEnum] = foo, [barEnum] = bar };
...
funcType p = funcTable[fooEnum];
p = funcTable[p()];
†This was raised in comments and in Paul's answer https://stackoverflow.com/a/50640762/315052, but presented here for completeness.