Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function expecting arguments and returning a pointer to a void function

Tags:

c++

pointers

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.

like image 408
alexanderk409 Avatar asked Dec 25 '22 01:12

alexanderk409


1 Answers

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);
like image 116
Sam Varshavchik Avatar answered Dec 26 '22 13:12

Sam Varshavchik