如何实现通用的回调在C ++中 [英] How to implement generic callbacks in C++

查看:123
本文介绍了如何实现通用的回调在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原谅我的无知在问这个基本问题,但我已经变得如此习惯于使用Python在哪里这样的事情是微不足道的,我已经完全忘记了我怎么会用C尝试此++。

Forgive my ignorance in asking this basic question but I've become so used to using Python where this sort of thing is trivial that I've completely forgotten how I would attempt this in C++.

欲能够回调传递给在后台执行一个缓慢的过程的功能,并且具有它后来被称为当该过程完成。此回调可以是一个免费的功能,静态函数,或成员函数。我还希望能够注入一些任意参数在里面上下文。 (即实现一个非常贫穷的人的协同程序,在某种程度上)。最重要的是,此功能将始终以一个std :: string的,这是过程的输出。我不介意这种说法在最后的回调参数列表中的位置是固定的。

I want to be able to pass a callback to a function that performs a slow process in the background, and have it called later when the process is complete. This callback could be a free function, a static function, or a member function. I'd also like to be able to inject some arbitrary arguments in there for context. (ie. Implementing a very poor man's coroutine, in a way.) On top of that, this function will always take a std::string, which is the output of the process. I don't mind if the position of this argument in the final callback parameter list is fixed.

给我的感觉,答案将涉及的boost ::绑定和boost ::功能,但同时他们钻营,只是我不能为了创建任意可调用(摸出precise调用,这将是必要的采取单个字符串),将它们存储在后台进程,并与字符串参数正确地调用调用。

I get the feeling that the answer will involve boost::bind and boost::function but I can't work out the precise invocations that would be necessary in order to create arbitrary callables (while currying them to just take a single string), store them in the background process, and invoke the callable correctly with the string parameter.

推荐答案

回调应被存储为的boost ::功能<无效,标准::字符串> 。然后你可以使用的boost ::绑定其他任何函数签名转换到这样一个对象,通过结合其它参数。

The callback should be stored as a boost::function<void, std::string>. Then you can use boost::bind to "convert" any other function signature to such an object, by binding the other parameters.

我还没有尝试编译这一点,但它应该反正显示的总体思路

I've not tried to compile this, but it should show the general idea anyways

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 ) ); 
}

这篇关于如何实现通用的回调在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆