C ++ std :: function绑定库之间的回调,而不暴露方法API

时间:2016-07-22 17:43:29

标签: c++ c++11 callback std-function stdbind

在提出这个问题之前,我已经查看了很多链接,并在C ++中对std :: function,std:bind和callbacks进行了大量阅读。据我了解,这个概念主要是为了让事件处理程序在某个事件发生后通知监听器。我正在努力寻找适合跨库边界的正确实现,因为我是这种编程风格的新手。

以下是我需要实施的情况或设计:

我有一个库A,它在一个类中有一个私有函数,它接受某些数据并进行一些处理。有一个libraryB提供了库A中的函数所需的相同数据,但是libraryB公开了一个std ::函数来接收该数据。其他库需要将其函数绑定到其回调以接收数据。所以,我需要将libraryA' s func绑定到我的Application类中的libraryB< std :: function。

Inside libraryA {

Class A {

private:
    AA objAA;
}

Class AA {

private:
    void func(int x) {
        //this is the function I want to tie to calback in library libB without exposing the method api
        //How can I expose a public api to return the address of this function so that the app can bind it to libraryB's callback ?
    }
}

}

Inside libraryB {

Class B {
public:
    void registerCallback(std::function<void (int)> callmePls) {
        m_callback = callmePls;
    }
private:
    typedef std::function<void (int)> theCallback;
    theCallback m_callback;
}

}


Inside my Application which uses both libraryA & libraryB {
//How can I bind/assign “func” in libraryA to the callback in libraryB ?
}

如何从库A公开公共API以返回感兴趣的函数的地址,以便应用程序可以将其绑定到libraryB的回调? 如何将libraryA中的“func”绑定/赋值给libraryB中的回调?

1 个答案:

答案 0 :(得分:0)

.cpp文件(不在标题中)中实现了主体:

 class A {
 public:
   void listen(int x) {
     objAA.func(x);
   }

   std::function<void(int)> get_listener() {
     return [this](int x){ x.objAA.func(x); };
   }

   void listen_to( std::function< void( std::function< void(int) > ) > f ) {
     f( [this](int x){ x.objAA.func(x); } );
   }

在这里,你必须做一些体操才能registerCallback进入listen_to

实际上,后面的内容更抽象,但它们实际上并不会阻止您调用func