Reputation: 55
The C++ code below is a simplified version of what I want to do, just to display the general structure.
In each case of the "primary_function()" the structure is identical:
function() + 2
The only thing that changes is the function that is used (function 1, 2, 3, or 4).
Is there a more efficient way to do this so that I am not "repeating" code in each case? Thank you.
#include <iostream>
using namespace std;
int function1(int a){
return a;
}
int function2(int b){
return b*b;
}
int function3(int c){
return c*c + c;
}
int function4(int d){
return 5*d;
}
int primary_function(int x, int selection){
switch(selection){
case(1):
return function1(x) + 2;
break;
case(2):
return function2(x) + 2;
break;
case(3):
return function3(x) + 2;
break;
case(4):
return function4(x) + 2;
break;
}
}
int main(){
cout << primary_function(6,1) << endl;
cout << primary_function(6,2) << endl;
cout << primary_function(6,3) << endl;
cout << primary_function(6,4) << endl;
return 0;
}
Upvotes: 0
Views: 113
Reputation: 9535
You can use an array of function pointers as follows:
int primary_function(int x, int selection) {
using fn_ptr_t = int (*)(int);
static fn_ptr_t functions[] = {
function1,
function2,
function3,
function4
};
return functions[selection - 1](x) + 2;
}
You can also use std::function<int(int)>
as the item type of the array which would allow you to use lambdas, even with closures, in the array instead of only named functions.
Upvotes: 3