I am writing a program for minimization. It has two classes. Class A which does the minimization and Class B which prepares the objective function to be minimized. I need to pass the objective function provided by Class B as a member function to Class A, then the member function will be minimized.
I need to know what is the most efficient way to do that. Particularly, I have compilation errors regarding passing the function from class B to class A.
#include <functional>
#include <vector>
template <class value_type>
struct A
{
using func_type = std::function<value_type(std::vector<value_type>&)>;
A(std::vector<value_type>& p, func_type f) : _params(p), _func(f)
{
}
void minimize() {}
private:
std::vector<value_type>& _params;
func_type _func;
};
struct B
{
/* some member variables*/
using param_type = std::vector<double>;
double objective_func(param_type&) { return 0.0; }
void do_minimization()
{
auto func = [&](param_type& P) { return objective_func(P); };
A<double>(p, func).minimize();
}
private:
param_type p;
};
Obviously simplified code, but one wonders why A is a class and not a function and why it needs access to the function if it only manipulates the vector.
Thank you so much.
It is the simplified code, because the actual code is too long. There are lots of different functions in each of the classes.
Actually, the minimize function changes one element of P per iteration and pass the new P to the objective_func to see if the new change minimizes the function or not.
for example: objective_func receives a vector P1 and then updates P using P1 to return the results. This will be done thousands of time to find the optimized P.
Based on your implementation, the objective function is receiving the address of the member variable P.