Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch between 2 function sets in C++?

Is there a way, I can switch between 2 similar function sets (C/C++) in an effective way? To explain better what I mean, lets say I have 2 sets of global functions like:

void a_someCoolFunction();
void a_anotherCoolFunction(int withParameters);
…

void b_someCoolFunction();
void b_anotherCoolFunction(int withParameters);
…

And I want to able to "switch" in my program at runtime which one is used. BUT: I dont want to have one if condition at every function, like:

void inline someCoolFunction(){
    if(someState = A_STATE){
        a_someCoolFunction();
    }else{
        b_someCoolFunction();
    }
}

Because, I expect that every function is called a lot in my mainloop - so It would be preferable if I could do something like this (at start of my mainloop or when someState is changed):

if(someState = A_STATE){
    useFunctionsOfType = a;
}else{
    useFunctionsOfType = b;
}

and then simply call

useFunctionsOfType _someCoolFunction();

I hope its understandable what I mean… My Background: Im writing an App, that should be able to handle OpenGL ES 1.1 and OpenGL ES 2.0 both properly - but I dont want to write every render Method 2 times (like: renderOpenGL1() and renderOpenGL2() I would rather to write only render()). I already have similiar Methods like: glLoadIdentity(); myLoadIdentity(); … But need a way to switch between these two somehow. Is there any way to accomplish this in an efficent way?

like image 460
Constantin Avatar asked Feb 06 '11 22:02

Constantin


Video Answer


1 Answers

Several options, including (but not limited to):

  • Use function pointers.
  • Wrap them in classes, and use polymorphism.
  • Have two separate copies of the loop.

But please profile to ensure this is actually a problem, before you make any large changes to your code.

like image 102
Oliver Charlesworth Avatar answered Sep 28 '22 08:09

Oliver Charlesworth