In python I can pass a reference to a function into a class and then use it again later by
calling a class variable with the required arguments. As below:
def add_together(a, b):
return a + b
class Function:
def __init__(self,action,name,num_inputs=2,num_outputs=1):
self.action = action
self.num_inputs = num_inputs
self.num_outputs = num_outputs
self.name = name
self.f_type = True
def solve(self,*args):
return self.action(*args)
f = Function(add_together,"'add'")
print f.action(3,5)
I’m moving the code to c++ for speed, but not knowing much C++, I’ve had some trouble finding out how to achieve the same. See (weak) attempt below. I’m keen to keep the logic as similar as possible.
I would like to know two things,
- How can I pass a reference to a function into a class?
- The *args in c++ I believe would work through overloading but I am unsure how to load and unload the variables.
Kind of basic questions I know but I am struggling to solve with Google.
Attempt in c++
double add_together(double a, double b) {
return a + b;
}
class Function {
public:
Function(int ni, double act) {
int num_inputs = ni;
double action = act;
}
protected:
int num_inputs;
double action;
};
Function f(2,add_together);
Function pointers seem to be what you are looking for. The typedef at the start isn’t necessary but it does simplify the syntax.
Also you have an error in your constructor. You redecalred the member variables
num_inputsandactionas local variables in the constructor. I don’t think you wanted to do that.