本文介绍了如何将一个方法作为回调传递给另一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于使用tr1 :: function回调的问题。我定义了以下内容:

I have a question regarding callbacks using tr1::function. I've defined the following:

  class SomeClass {
    public:
      typedef std::tr1::function<void(unsigned char*, int)> Callback;
      void registerCallback(Callback);
    private:
      Callback callback;
  }

我定义了另一个类:

  class SomeOtherClass {
      void myCallback(unsigned char*, int);

  }



现在我想注册我的函数'myCallback'在类'SomeClass'使用方法'registerCallback'。但是,它不工作。我已经看了关于功能的boost文档,似乎合法使用(成员)类的方法的回调。我错了吗?

Now I want to register my function 'myCallback' as callback at class 'SomeClass'using the method 'registerCallback'. However, it is not working. I've had a look on the boost documentation on the function and it seems legit to use (member) methods of a class for callbacks. Am I wrong?

提前感谢!

推荐答案

参数,一个这个指针,以便知道调用该函数的对象。通常,它是隐藏的,但是要绑定一个成员函数到std :: function,你需要显式地提供类型的模板参数。

Member functions have an implicit first parameter, a this pointer so as to know which object to call the function on. Normally, it's hidden from you, but to bind a member function to std::function, you need to explicitly provide the class type in template parameter.

#include <functional>
#include <iostream>

struct Callback_t {
    void myCallback(int)
    {
        std::cout << "You called me?";
    }
};

class SomeClass {
public:
    SomeClass() : callback() { }
    typedef std::function<void(Callback_t*, int)> Callback;
                           //  ^^^^^^^^^^^

    void registerCallback(const Callback& c)
    {
        callback = c;
    }

    void callOn(Callback_t* p)
    {
        callback(p, 42);
    }
private:
    Callback callback;
};

int main()
{
    SomeClass sc;
    sc.registerCallback(&Callback_t::myCallback);

    Callback_t cb; // we need an instance of Callback_t to call a member on
    sc.callOn(&cb);
}

输出: $ c>;

Output: You called me?;

这篇关于如何将一个方法作为回调传递给另一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 12:20