Question

I have a class in C++ that is also a functor, as well as contains another member function. The return values of the functions depend on both x and alpha.

class A {
    A(double x) : x(x) { }
    /* snip */
    double operator() (double x);
    double derivative(double x);
    double alpha = 1.0;
}

I want to access both of these and store them in function objects in another class like this:

class B {
    /* snip */
    function<double(double)> f;
    function<double(double)> d;
}

I want to initialize both f and d in B's constructor. I figured that the following can initialize f

this->f = A(1.0);

OR

A a(1.0);
this->f = a;

My question is: How can I achieve the same initialisation for d? I am using g++ 4.8.1 (C++11 syntax)

Was it helpful?

Solution

You need to bind the member function to an instance of A:

d = std::bind(&A::derivative, &a, std::placeholders::_1);

where a is an instance of A. This is because member functions have an implicit first parameter for this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top