Sign in to follow this  
Timjanmannen

Function pointer returning a function pointer of the same kind

Recommended Posts

Hiya all. I am wondering, is it possible to make a function pointer that returns another function pointer of the same kind(the returned function pointer returns a function pointer of the same kind and so on) and how do you do it? Thanks

Share this post


Link to post
Share on other sites
No, that's a circular definition.

You're trying to tell the compiler to create a new type with only the information that the new tpye is equal to itself.


What are you trying to accomlish by this? We can probably work out a solution if we know what problem you're trying to solve.

Share this post


Link to post
Share on other sites
*** absolute qualifier snipped ***

EDIT: Apparently you can, but not with regular function pointer syntax. (see Enigma's link)

[Edited by - stylin on October 5, 2005 9:31:19 AM]

Share this post


Link to post
Share on other sites
Or you could always throw away type-safety and return it as a void pointer.
I've used this kind of design (with a slightly different method) for a parser state machine.

Share this post


Link to post
Share on other sites
struct FuncPtr_;
typedef FuncPtr_ (*FuncPtr)();

struct FuncPtr_
{

FuncPtr_(FuncPtr pp)
:
p(pp)
{
}

operator FuncPtr()
{
return p;
}

FuncPtr p;

};

FuncPtr_ f()
{
return f; // natural return syntax
}

int main()
{
FuncPtr p = f(); // natural usage syntax
p();
}

(Thanks Herb).

Enigma

Share this post


Link to post
Share on other sites
#include <stdio.h>
#include <conio.h>
#include <windows.h>

typedef void* (*fp) ();

void* g();

void* f()
{
printf("f\n");
Sleep(100);
return g;
}
void* g()
{
printf("g\n");
Sleep(100);
return f;
}
void main()
{
fp r=(fp)f;
while(!kbhit()) r=(fp)r();
}

Share this post


Link to post
Share on other sites
I was just making an experiment, like, a main function that would look something like

main()
{

funcptr=menu();
while(funcptr) funcptr=(*funcptr)()

}

I saw the recursion, i just wondered if there was some kind of 'hack' to get around it :)

btw, how do you make a code-box on these forums?

Share this post


Link to post
Share on other sites
For small snippets like stylin posted use [code] or <tt>. For scrollable source boxes for larger snippets use [source], with an optional lang= attribute. See also the FAQ.

Enigma

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this