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的声明是什么?
发布于 2011-08-05 23:27:21
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类型也是可能的,例如传递引用到常量,而不是传递引用到非常量)
发布于 2011-08-05 22:32:26
试试这个:
boost::bind(&Foo::f1, object, _1, _2);object是类Foo的一个实例。_1和_2是参数占位符。
https://stackoverflow.com/questions/6957929
复制相似问题