first of all I know that this is not possible in C++. But I hope someone can tell be a workaround for my problem. I have a class which represents a mathematical function:
class myClass:
{
private:
public:
myClass() {};
double value(double, double){ /* doing some complicated calculation here */} };
double integrate { /*calc*/ return integral; };
}
In integrate()
I want to create a struct with a reference to value()
. The struct is defined as follows:
struct gsl_monte_function_struct {
double (*f)(double * x_array, size_t dim, void * params);
size_t dim;
void * params;
};
(I need this struct to call the Monte-Carlo integration routines from GSL)
As said before I know that this is forbidden in C++. But is there any possibility to use gsl_monte_function_struct
with a member function of myClass? If it is not possible that myClass
can integrate itself, is it possible to call gsl_monte_function_struct
from outside the class with value()
as reference? Thanks in advance!
If understand you corretly, you want a pointer to a member function of
myClass
. You can achieve this by declaring the member function pointer as:This function can later be called on an instance as:
Alternatively you can use
std::bind
to create a function object which can be called as an ordinary function without having to keep track of the instance on which it is called after the call tostd::bind
:Ok so far I found two solutions:
1) (General solution) Using an abstract base class which has a static pointer to the current instance and a static function that calls a function of the derived class. The static function can be used with a function pointer.
Example:
2) (Solution specific to my problem) Fortunatly the desired function accepts a parameter pointer, which I can use to pass the current object: