How to get a class member to behave like a function pointer using Boost

87 views Asked by At

I would like to have a class member function behave like a function pointer. I need this behavior to integrate my own classes into some existing code.

It seems that this may be possible using Boost::function and Boost::bind, but I can't seem to get it working. The following code is a minimal example that I am using to test my implementation. The last line in the main() program is what I would like to be able to do.

Any help is greatly appreciated. I am using g++ and Boost 1.46.

// Includes
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <stdio.h>
using namespace std;

// Define a pure virtual base class
class Base{
    public:
        virtual double value(double v, double t) = 0;
};

// Define a derived class
class Derived : public Base{
    public:
        double value(double v, double t){
            return v*t;
        }
};

// Main program
int main(){

// A derived class
boost::shared_ptr<Derived> p(new Derived);

// Use class directly
printf("value = %f\n", p->value(100, 1));

// Create a boost::function
boost::function< double (Derived*, double, double) > f;
f = &Derived::value;
printf("f(&A, 100, 2) = %f\n", f(p.get(), 100, 2));

// Use boost::bind
printf("bind f(100,3) = %f\n", boost::bind(&Derived::value, p, _1, _2)(100,3));

// Make a boost::function to the binded operation???
boost::function< double (double, double) > f2;

f2 = boost::bind(&Derived::value, p.get()); // This is wrong

printf("f2(100,4) = %f\n", f2(100,4)); // I want to be able to do this!
}
1

There are 1 answers

1
Attila On BEST ANSWER

Based on the documentation (See section "Using bind with pointers to members"), you need to specify that the function has two parameters:

f2=bind(&Derived::value, p.get(), _1, _2);
f2(100, 4);  // p.get()->value(100, 4)