alexanderk409 alexanderk409 - 2 months ago 16
C++ Question

Function expecting arguments and returning a pointer to a void function

I have several void-functions that do some important things in my code.

void function1(Myclass class1, int myvar)
{
// do some stuff
}

void function2(Myclass class1, int myvar)
{
// do some other stuff
}

// ... maybe some more similar functions


I want to create a function that would return a pointer to any of these functions depending on arguments I pass. I don't know how to do it. I want to have something like

void* choosefunction(int i, int j)
{
if (i == j) return (void*)function1;
else return (void *)function2;
}


Then I would just call them by this pointer.

void *(*ptrProcFunc)(int,int);
ptrProcFunc = &choosefunction;
(*ptrr)() = ptrProcFunc(i,j);
ptrr(class1,myvar);


How to do it correctly? Thank you.

Answer

typedef is your friend.

typedef void (*func_ptr)(Myclass, int);

func_ptr choosefunction(int i, int j)
{
   if (i == j) return &function1;
   else return &function2;
}

Then:

func_ptr ptrr = choosefunction(i,j);

ptrr(class1,myvar);