如何在C++中实现通用回调

Kyl*_*tan 21 c++ boost boost-bind

原谅我对这个基本问题的无知,但我已经习惯了使用Python,这种事情是微不足道的,我已经完全忘记了如何在C++中尝试这一点.

我希望能够将回调传递给在后台执行缓慢进程的函数,并在进程完成后稍后调用它.此回调可以是自由函数,静态函数或成员函数.我也希望能够在那里注入一些任意的参数用于上下文.(即,在某种程度上实现一个非常差的人的协程.)最重要的是,这个函数将始终采用std :: string,这是进程的输出.我不介意这个参数在最终回调参数列表中的位置是否固定.

我觉得答案将涉及boost :: bind和boost :: function但是我无法确定为了创建任意的callables而需要的精确调用(同时将它们调整为只需要一个字符串),将它们存储在后台进程中,并使用string参数正确调用callable.

And*_*bel 17

回调应存储为boost::function<void, std::string>.然后,您可以boost::bind通过绑定其他参数,将任何其他函数签名"转换"为此类对象.

我没有尝试编译它,但它应该显示一般的想法

void DoLongOperation(boost::function<void, const std::string&> callback)
{
  std::string result = DoSomeLengthyStuff();
  callback(result);
}


void CompleteRoutine1(const std::string&);
void CompleteRoutine2(int param, const std::string&);

// Calling examples
DoLongOperation(&CompleteRoutine1); // Matches directly
DoLongOperation(boost::bind(&CompleteRoutine2, 7, _1)); // int parameter is bound to constant.

// This one is thanks to David Rodríguez comment below, but reformatted here:
struct S 
{ 
  void f( std::string const & );
};

int main() 
{ 
  S s;
  DoLongOperation( boost::bind( &S::f, &s, _1 ) ); 
}
Run Code Online (Sandbox Code Playgroud)

  • +1和成员函数示例:`struct S {void f(std :: string const&); }; int main(){S s; DoLongOperation(boost :: bind(&S :: f,&s,_1)); 你可以根据需要添加额外的参数,只需记住`boost :: bind`将复制参数. (3认同)