C++ noobboost::bind成员函数回调问题 #包括 #包括 使用名称空间std; 使用boost::bind; 甲级{ 公众: 无效打印(字符串和s){ cout
将C++ noobboost::bind成员函数回调问题 #包括 #包括 使用名称空间std; 使用boost::bind; 甲级{ 公众: 无效打印(字符串和s){ cout,c++,boost,bind,C++,Boost,Bind,将typedef void(*callback)();替换为typedef boost::function callback; 绑定函数不会生成普通函数,因此不能仅将其存储在常规函数指针中。但是,boost::function能够处理任何东西,只要它可以使用正确的签名调用,这就是您想要的。它将与函数指针或用bind创建的函子一起工作 在对您的代码进行了一些更正后,我得出了以下结论: #include <boost/bind.hpp> #include <iostream>
typedef void(*callback)();
替换为typedef boost::function callback;
绑定函数不会生成普通函数,因此不能仅将其存储在常规函数指针中。但是,boost::function
能够处理任何东西,只要它可以使用正确的签名调用,这就是您想要的。它将与函数指针或用bind创建的函子一起工作
在对您的代码进行了一些更正后,我得出了以下结论:
#include <boost/bind.hpp>
#include <iostream>
using namespace std;
using boost::bind;
class A {
public:
void print(string &s) {
cout << s.c_str() << endl;
}
};
typedef void (*callback)();
class B {
public:
void set_callback(callback cb) {
m_cb = cb;
}
void do_callback() {
m_cb();
}
private:
callback m_cb;
};
void main() {
A a;
B b;
string s("message");
b.set_callback(bind(A::print, &a, s));
b.do_callback();
}
#包括
#包括
#包括
//我更喜欢显式名称空间,但这是一个偏好的问题
甲级{
公众:
//除非需要修改参数,否则更喜欢常量引用而不是常规引用!
无效打印(常量std::string&s){
//这里不需要.c_str(),因为我知道如何输出std::字符串(很好:-)
标准::cout
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
// i prefer explicit namespaces, but that's a matter of preference
class A {
public:
// prefer const refs to regular refs unless you need to modify the argument!
void print(const std::string &s) {
// no need for .c_str() here, cout knows how to output a std::string just fine :-)
std::cout << s << std::endl;
}
};
// holds any arity 0 callable "thing" which returns void
typedef boost::function<void()> callback;
class B {
public:
void set_callback(callback cb) {
m_cb = cb;
}
void do_callback() {
m_cb();
}
private:
callback m_cb;
};
void regular_function() {
std::cout << "regular!" << std::endl;
}
// the return type for main is int, never anything else
// however, in c++, you may omit the "return 0;" from main (and only main)
// which will have the same effect as if you had a "return 0;" as the last line
// of main
int main() {
A a;
B b;
std::string s("message");
// you forget the "&" here before A::print!
b.set_callback(boost::bind(&A::print, &a, s));
b.do_callback();
// this will work for regular function pointers too, yay!
b.set_callback(regular_function);
b.do_callback();
}