Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap between functions implementation?

Tags:

c++

c++11

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.

like image 281
morbyosef Avatar asked Nov 13 '18 14:11

morbyosef


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
like image 170
lubgr Avatar answered Sep 30 '22 15:09

lubgr


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.

like image 21
Matthieu Brucher Avatar answered Sep 30 '22 16:09

Matthieu Brucher