not-a-user
not-a-user

Reputation: 4327

How to declare a function with a parameter that has the same signature as the function?

How can I declare a function that takes a function pointer, to a function with the same signature as the function, as an argument?

In gcc, what does not work is

foo_t * f(bar_t const *, typeof(f) *);

or

typedef foo_t (* f_t)(bar_t const *, f_t);
f_t f;

I do not want to cast to void * and back if possible.

Upvotes: 2

Views: 90

Answers (1)

Useless
Useless

Reputation: 67772

You can use a forward-declared struct to break the type recursion (this is roughly similar to a functor or callable object in C++)

struct Func;
typedef foo_t *(*FuncFunc)(bar_t const *b, struct Func *);

struct Func { FuncFunc callee; };
foo_t * f(bar_t const *b, struct Func *func) {
  Func nextfunc = { f };
  return func->callee(b, nextfunc); /* <-- infinite recursion */
}

Using void/cast and varargs are both hacks - the above at least preserves type information.

Upvotes: 2

Related Questions