如何使用Boost使类成员像函数指针一样运行

时间:2012-05-16 15:31:35

标签: boost-bind member-function-pointers boost-function

我希望类成员函数的行为类似于函数指针。我需要这种行为来将我自己的类集成到现有代码中。

看起来这可能是使用Boost :: function和Boost :: bind的,但我似乎无法让它工作。以下代码是我用来测试我的实现的最小示例。 main()程序的最后一行是我希望能够做到的。

非常感谢任何帮助。我正在使用g ++和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 个答案:

答案 0 :(得分:0)

基于documentation(请参阅“使用带指针指向成员的绑定”一节),您需要指定该函数有两个参数:

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