代码之家  ›  专栏  ›  技术社区  ›  L3M0L

如何将派生类中的成员函数作为回调传递?

  •  1
  • L3M0L  · 技术社区  · 7 年前

    我有一节简单的课 X

    class X {
    public:
        template<typename T>
        void doSomething(T &completion) {
            std::cout << completion(10) << std::endl;
        }
    };
    

    A B

    class A {
    public: 
     // some code
     X* c;
    };
    
    class B : public A {
    public:
      int test(int x) {
        return x * x;
      }
    
      void execute() {
       auto lambda = [] (int x) { cout << x * 50 << endl; return x * 100; };
       c->doSomething(lambda); // works
       c->doSomething(&B::test); // does not work
      }
    };
    

    我想传给 doSomething B类 )但它不起作用:/

    3 回复  |  直到 7 年前
        1
  •  5
  •   Geezer    7 年前

    如何将派生类中的成员函数作为回调传递?

    你的问题与我无关 B 作为一个儿童班。你的问题是你不是 这个 test() 它的实例。

    using std::bind 返回

    c->doSomething(std::bind(&B::test, this, std::placeholders::_1));
    

    别忘了 #include <functional> ,

    λ 通过把 this lambda captures

    c->doSomething([this](int x){ return this->test(x); });
    

    注意:一定要换 doSomething() 的参数为 所以它可以在临时对象和其他对象中正确地接受所有这些回调。应该是这样的:

    template<typename T>
    void doSomething(T&& completion)
    
        2
  •  3
  •   Derek T. Jones    7 年前

    B::test 一个静态方法,它将按所写的方式工作:

    static int test(int x) {
        return x * x;
    }
    // ...
    c->doSomething(&B::test);
    

    this 指针)。

    如果

    c->doSomething([this] (int x) { return this->test(x); });
    

    注: 在编译这段代码时,我需要更改 doSomething & 关闭 T :

    template<typename T>
    void doSomething(T completion) {
        std::cout << completion(10) << std::endl;
    }
    

    这可以防止在函数指针类型上放置l值或非常量约束,从而防止编译器创建临时lambda函数。

        3
  •  1
  •   Rob Starling    7 年前

    你的意思是 c->doSomething([this](int x) { return this->test(x); }); ?