I often use function pointers in my c++code, always in accordance with this simple canonical example (for example, functions have the same I / O, but the desired operation is known only at runtime)
#include <iostream>
using namespace std;
int add(int first, int second){
return first + second;
}
int subtract(int first, int second){
return first - second;
}
int operation(int first, int second, int (*functocall)(int, int)){
return (*functocall)(first, second);
}
int main(){
int a, b;
int (*plus)(int, int) = add;
int (*minus)(int, int) = subtract;
a = operation(7, 5, plus);
b = operation(20, a, minus);
cout << "a = " << a << " and b = " << b << endl;
return 0;
}
I started using this some time ago simply because I found it easier to use. As I learn more about C ++, I wonder: is this construct bad in terms of performance in this context ? If so, why and what are the best options for c++11-ish?
, ( )
EDIT:
Im x86.