c++ - Switching between function implementations with function pointers -


i have 2 versions of c function trade off each other in terms of speed , memory usage. these functions located in .cpp file shared across several programs. want use function pointer can switch , forth between 2 implementations, , have changes carry through across files in program.

combination.h (extract)

long chooserecursive (int n, int r); long chooselookup (int n, int r); void foo (int n, int r); static long (*choose)(int, int) = chooserecursive; 

combination.cpp (extract)

long chooserecursive (int n, int r) { cerr << "recursive\n"; } long chooselookup (int n, int r) { cerr << "lookup\n"; } void foo (int n, int r) { choose(n, r); } 

main.cpp (extract)

int main(int argc, char* argv []) {     choose = chooselookup;     choose(10, 5);     foo(10, 5); } 

the output is:

lookup recursive 

why foo function not use chooselookup instead of chooserecursive? how fix this? there better approach can use accomplish same goal?

thank in advance help!

as things stand, each .cpp file includes combination.h has own static variable choose. code in main updates main.cpp's copy not version in combination.cpp.

one easy way fix change combination.h declare choose extern

extern long (*choose)(int, int); 

then implement/initialise in combination.cpp

long (*choose)(int, int) = chooserecursive; 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -