How to swap between functions implementation?

Viewed 279

Is there any way to swap between two functions implementation in C++ ?

Something like this:

void printA(); // print a char
void printB(); // print b char

printA(); // output: a
printB(); // output: b

functionSwap(printA, printB);

printA(); // output: b
printB(); // output: a

I want to use it with the ExitProcess function.

2 Answers

You can bind a pointer to both functions in two variables and swap those.

void (*f1)() = printA;
void (*f2)() = printB;

f1(); // output: a
f2(); // output: b

std::swap(f1, f2);

f1(); // output: b
f2(); // output: a

You need to wrap them in objects (or pointers to functions):

std::function<void()> myprintA = printA;
std::function<void()> myprintB = printB;

std::swap(myprintA, myprintB);

myprintA();
myprintB();

Otherwise, you are working with symbols themselves, and you can't swap this.

Related