How can I typedef a function pointer that takes a function of its own type as an argument?

↘锁芯ラ 提交于 2019-12-18 05:45:11

问题


Example: A function that takes a function (that takes a function (that ...) and an int) and an int.

typedef void(*Func)(void (*)(void (*)(...), int), int);

It explodes recursively where (...). Is there a fundamental reason this can't be done or is there another syntax? It seems to me it should be possible without a cast. I'm really trying to pass a dispatch-table but I could figure that out if I could just pass this one type.


回答1:


You can wrap the function pointer in a struct:

struct fnptr_struct;
typedef void (*fnptr)(struct fnptr_struct *);
struct fnptr_struct {
  fnptr fp;
};

I'm not sure if this is an improvement on casting. I suspect that it's impossible without the struct because C requires types to be defined before they are used and there's no opaque syntax for typedef.




回答2:


It's impossible to do directly. Your only options are to make the function pointer argument accept unspecified arguments, or to accept a pointer to a structure containing the function pointer, as Dave suggested.

// Define fnptr as a pointer to a function returning void, and which takes one
// argument of type 'pointer to a function returning void and taking
// an unspecified number of parameters of unspecified types'
typedef void (*fnptr)(void (*)());


来源:https://stackoverflow.com/questions/816356/how-can-i-typedef-a-function-pointer-that-takes-a-function-of-its-own-type-as-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!