boost绑定类函数指针

时间:2011-08-05 14:28:24

标签: c++ boost-bind boost-function

class Foo 
{
    double f1( int x, std::string s1 );
    double f2( int x, SomeClass s2 );
}

我希望能够在没有foo实例的情况下绑定Foo.f1的s1以在essense中创建

typedef double (Foo::* MyFooFunc)( int ) 

MyFooFunc func1 = boost::bind( &Foo::f1, _1, _2, "some string" );
MyFooFunc func2 = boost::bind( &Foo::f2, _1, _2, SomeClass );

然后我将func1和func2作为参数传递给其他函数,其中Foo最终被绑定在其中:

void SomeOtherFunction( MyFooFunc func )
{
     Foo foo;
     boost::function< double (int) > finalFunc =
          boost::bind( func, foo, _1 );
}

问题: 这可能吗?如果是,1)如何实现它? 2)MyFooFunc的声明是什么?

2 个答案:

答案 0 :(得分:4)

typedef double (Foo::* MyFooFunc)( int );

MyFooFunc func1 = boost::bind( &Foo::f1, _1, _2, "some string" );

boost::bind的结果不是指向成员的指针,因此func1无法在第二行上初始化。 boost::bind的结果是未指定的类型(取决于参数)。如果您使用的是C ++ 0x,则将bind调用结果命名的最简单方法是使用auto

auto func1 = boost::bind( &Foo::f1, _1, _2, "some string" );

另一种简单的方法(不限于C ++ 03)只是不命名结果,而是在现场使用它:

SomeOtherFunction(boost::bind(&Foo::f1, _1, _2, "some string"));

或者,您可以使用类型删除将boost::bind的结果存储到您似乎熟悉的boost::function中。 boost::function<double(Foo&, int)>是可能的,但不是唯一的选择。


我们现在需要找到SomeOtherFunction的相应签名:再次,无法从调用boost::bind的结果初始化指向成员的指针,因此void SomeOtherFunction(MyFooFunc func);赢了工作。您可以将该功能改为模板:

template<typename Func>
void SomeOtherFunction( Func func )
{
     Foo foo;
     boost::function< double (int) > finalFunc =
          boost::bind( func, foo, _1 );
}

如果模板不是优选的,那么你必须使用某种类型的擦除,例如boost::function

void SomeOtherFunction(boost::function<double(Foo&, int)> const& func);

(再次可以使用其他boost::function类型,具体取决于传递ref-to-const而不是ref-to-non-const等细节

答案 1 :(得分:0)

试试这个:

boost::bind(&Foo::f1, object, _1, _2);

object是Foo类的一个实例。 _1和_2是参数占位符。

相关问题