Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointer pointing to a function that takes a function pointer

How do I declare a function pointer that points to a function taking the same function pointer as the argument?

I've tried the following without success:

typedef void (*fnptr)(void (*)());

void func(fnptr)
{
    /* ... */
}

void func2(fnptr)
{
    /* ... */
}

void main()
{
    fnptr fn = &func;
    func2(fn);
}

Is this possible?

like image 821
Oskar Walker Avatar asked May 25 '11 17:05

Oskar Walker


People also ask

Can a function pointer be used to call a function?

Function pointers in C can be used to create function calls to which they point. This allows programmers to pass them to functions as arguments. Such functions passed as an argument to other functions are also called callback functions.

Which of the following is a pointer pointing to function?

In the above declaration, *ip is a pointer that points to a function which returns an int value and accepts an integer value as an argument.

What is a function pointer that allows you to invoke a procedure indirectly?

Function compute_sum in turn invokes one of the two functions indirectly by dereferencing its function pointer argument funcp multiple times, adding together the values that the invoked function returns and returning the resulting sum.


1 Answers

I very much doubt it, but you can get the needed recursion by introducing a struct.

struct Rec;

typedef void (*RecFun)(const Rec&);

struct Rec {
    RecFun fun;
};

Example of use:

#include <iostream>

void nothing(const Rec& rec) {}
Rec recNothing = { nothing };

void f(const Rec& rec)
{
    std::cout << "f\n";
    rec.fun(recNothing);
}
Rec recF = { f };

void g(const Rec& rec)
{
    std::cout << "g\n";
    rec.fun(recNothing);
}
Rec recG = { g };

int main()
{
    recF.fun(recG);
}

Update: As per the suggestions of Chris, Vitus, and Johannes, here are some convenient implicit conversions (as in Herb Sutter's GotW #57):

struct Rec;

typedef void (*RecFun)(const Rec&);

struct Rec {
    RecFun fun;
    Rec(RecFun fun) : fun(fun) {}
    operator RecFun() const { return fun; }
};
like image 52
antonakos Avatar answered Sep 23 '22 20:09

antonakos