2

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)

Abhra Basak
  • 382
  • 4
  • 13
  • 2
    Both of these "initializations" aren't, they're assignments. To initialize, you just want something like `: f(1.0)` in the constructor initializer list. – Kerrek SB Jan 04 '14 at 16:02

1 Answers1

5

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.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • That works great :) :) !! Though I'll still be on the look for a cleaner solution. – Abhra Basak Jan 04 '14 at 15:52
  • @AbhraBasak you will always need to pass an instance to a non-static member function, otherwise it cannot access any other non-static members. But if you do not need any of these, you can make `A::derivative` a static member function. That won't have an implicit 1st parameter. – juanchopanza Jan 04 '14 at 15:58
  • You are right. I just found a similar thread here: http://stackoverflow.com/questions/7582546/using-generic-stdfunction-objects-with-member-functions-in-one-class – Abhra Basak Jan 04 '14 at 16:18