请原谅我问了这个基本的问题,但我已经习惯于在这种琐碎的事情中使用Python,以至于我已经完全忘记了我将如何在C++中尝试。
我希望能够将回调传递给在后台执行缓慢进程的函数,并在该进程完成后调用它。此回调可以是自由函数、静态函数或成员函数。我也希望能够在其中注入一些任意的参数作为上下文。(即在某种程度上,实现一个非常可怜的人的协程。)最重要的是,此函数将始终接受std::string,它是进程的输出。我不介意这个参数在最终回调参数列表中的位置是固定的。
我感觉答案将涉及boost::bind和boost::function,但我无法计算出创建任意可调用(同时使它们只接受单个字符串)所需的精确调用,将它们存储在后台进程中,并使用字符串参数正确调用可调用。
发布于 2010-03-19 00:28:01
回调应该存储为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 ) );
}
发布于 2010-03-19 00:27:56
听起来您想使用Observer pattern。
发布于 2010-03-19 00:43:20
最简单的方法:
class Callback
{
public:
virtual ~Callback() {}
virtual Callback* clone() const = 0;
// Better to wrap the call (logging, try/catch, etc)
void execute(const std::string& result) { this->executeImpl(result); }
protected:
// Don't make sense to have them public
Callback() {}
Callback(const Callback&) {}
Callback& operator=(const Callback&) { return *this; }
private:
virtual void executeImpl(const std::string& result) = 0;
};
// Example
class Example: public Callback
{
public:
Example(int a, int b): Callback(), mA(a), mB(b) {}
virtual Example* clone() const { return new Example(*this); }
private:
virtual void executeImpl(const std::string& result) {}
int mA;
int mB;
};
然后,您可以将回调类(通过指针/引用)传递给进程。根据需要,类具有状态,并且可以在必要时进行复制(如果没有,则删除克隆)。
https://stackoverflow.com/questions/2471529
复制相似问题