传递回调成员函数的有效方法 [英] Efficient method of passing callback member function

查看:61
本文介绍了传递回调成员函数的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为输入处理程序类设计一种方法.这是一些伪代码...

I'm designing a method for an input handler class. Here is some pseudo code...

void InputHandler::ScanEvents( boost::function1< void, std::string& > &func ) {
   // Scan keys, determining string to pass
     // If string found, call func with string as its argument on object tied to func
}

我不确定如何实现此功能,甚至不确定是否可行,因为函数的重点是将其与调用者分开.这个想法是一个对象具有一个私有成员函数和一个保存它的boost :: function成员.每当它在其InputHandler上调用ScanEvents时,它都会传递该函数,因此只要找到适当的事件,ScanEvents便可以激活它".

I'm not exactly sure how to implement this, or if it is even possible, since the whole point of a function is to separate it from its caller. The idea is that an object has a private member function and a boost::function member that holds it. Whenever it calls ScanEvents on its InputHandler, it passes that function, so the ScanEvents can "activate it" whenever an appropriate event is found.

效率是一个令人关注的问题,因为这是性能非常重要的领域,并且经常调用此功能.

Efficiency is a concern, as this is in a domain where performance is important, and this function is called frequently.

P.S.我发誓我记得读过一本斯科特·迈耶(Scott Meyer)的书中的例子,但是我一生都找不到.也许是在现代C ++设计中...看起来....

P.S. I swear I remember reading an example like this in one of Scott Meyer's books, but I can't find it for the life of me. Maybe it was in Modern C++ Design...looking....

推荐答案

类似的东西

class Thingy
{
public:
    Thingy() : callback(bind(&Thingy::Callback, this, _1)) {}

    void DoStuff()
    {
        handler.ScanEvents(callback);
    }

private:
    InputHandler handler;
    function<void(string)> callback;

    void Callback(string s)
    {
        cout << "Called with " << s << endl;
    }
};

应该按照您的描述进行.但是对于回调来说,通过引用获取字符串可能会更有效.

ought to do what you describe. But it would probably be more efficient for the callback to take the string by reference.

这篇关于传递回调成员函数的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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