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

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

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 的声明是什么?

4

2 回答 2

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::bindboost::function您似乎熟悉的 a 中。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)

于 2011-08-05T15:27:20.863 回答
0

尝试这个:

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

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

于 2011-08-05T14:32:26.230 回答