【发布时间】:2016-04-14 23:32:20
【问题描述】:
我想通过公共函数将回调函数连接到升压信号。我可以很好地传递函数指针,但是如果我尝试使用 std::bind 传递成员函数,它将无法编译。给我错误说没有可行的转换。 App::SetCallback 函数参数应该使用什么类型?
#include <functional>
#include <boost/signal.hpp>
using namespace std::placeholders; // for _1, _2, _3...
//plain simple call back function
void SimpleCallback(int value) {
//do nothing
}
//class contains a boost::signal, set callback through a public function
class App {
public:
App() : sig_()
{}
typedef boost::signal<void (int value)> SigType;
typedef std::function<void (int value)> CallbackFunType;
//connect signal to a callback function
void SetCallback(CallbackFunType callback) {
sig_.connect(callback);
}
//private: //comment this out for testing purpose.
SigType sig_; //this is the boost::signal
};
//class that has member callback function
class MyCallback {
public:
MyCallback():
val(0), app()
{}
void MemberCb(int value){
val = value;
}
void Connect() {
auto bind_fun = std::bind(&MyCallback::MemberCb, this, _1);
app.SetCallback(bind_fun); //this will not compile, no viable conversion
app.sig_.connect(bind_fun); //this is fine
app.SetCallback(SimpleCallback); //this is fine
}
private:
int val;
App app;
};
int main(int argc, char **argv) {
MyCallback my_cb;
my_cb.Connect();
return 1;
}
----------------更新-----------------
更仔细地阅读升压信号文档,我了解到我可以通过插槽类型。这解决了我的问题
#include <functional>
#include <boost/signal.hpp>
using namespace std::placeholders; // for _1, _2, _3...
//plain simple call back function
void SimpleCallback(int value) {
//do nothing
}
//class contains a boost::signal, set callback through a public function
class App {
public:
App() : sig_()
{}
typedef boost::signal<void (int value)> SigType;
typedef SigType::slot_type CallbackFunType;
//typedef std::function<void (int value)> CallbackFunType;
//connect signal to a callback function
void SetCallback(CallbackFunType callback) {
sig_.connect(callback);
}
//private: //comment this out for testing purpose.
SigType sig_; //this is the boost::signal
};
//class that has member callback function
class MyCallback {
public:
MyCallback():
val(0), app()
{}
void MemberCb(int value){
val = value;
}
void Connect() {
auto bind_fun = std::bind(&MyCallback::MemberCb, this, _1);
app.SetCallback(bind_fun); //using SigType::slot_type
app.sig_.connect(bind_fun);
app.SetCallback(SimpleCallback);
}
private:
int val;
App app;
};
int main(int argc, char **argv) {
MyCallback my_cb;
my_cb.Connect();
return 1;
}
【问题讨论】:
-
Compiles with Boost 1.59 and g++ 5.3。也与 Apple LLVM 7.0.2 对应的任何 clang 版本对应。你在用什么构建?
-
@rhashimoto 很高兴知道它可以在您的平台上运行。我正在使用 Apple LLVM 7.1 和 Boost1.58 构建。我会尝试新版本的 boost,看看它是否有效。
-
不完全正确,但我可能会在这里使用 lambda 而不是
std::bind。
标签: c++ c++11 boost std-function stdbind