gpt4 book ai didi

c++ - 菜鸟boost::bind成员函数回调问题

转载 作者:太空狗 更新时间:2023-10-29 20:01:09 25 4
gpt4 key购买 nike

#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();

}

所以我想做的是让 A 流“消息”的打印方法在 b 的回调被激活时进行计算。我从 msvc10 收到意外数量的参数错误。我敢肯定这是 super 菜鸟的基础,我提前道歉。

最佳答案

替换typedef void (*callback)();typedef boost::function<void()> callback;

绑定(bind)函数不会生成普通函数,因此您不能只将其存储在常规函数指针中。然而,boost::function能够处理任何,只要它可以使用正确的签名调用,这就是您想要的。它将与函数指针或使用 bind 创建的仿函数一起工作。

在对您的代码进行了一些更正之后,我想出了这个:

#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();

}

关于c++ - 菜鸟boost::bind成员函数回调问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2907402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com