使用Boost function + bind 实现回调函数 编译错误...求教

kuai2361425 2015-02-11 11:12:58
先贴代码: 这是个简单测试类
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>

class AFun
{
public:
boost::function<void( boost::shared_ptr<AFun>&)> callback;

void run()
{
boost::shared_ptr<AFun> aFun = boost::shared_ptr<AFun>(this);
callback(aFun);
}

void print(){
std::cout<<"GGGGGGGGGGGGGGGGGGGGGGGGGGGG"<<std::endl;
}
};
class BFun
{
public:
void BindTestFun(boost::shared_ptr<AFun>& aFun){
aFun->print();
std::cout<<"SSSSSSSSSSSSSSSSSSSSSSSSSSSS"<<std::endl;
}
};


int _tmain(int argc, _TCHAR* argv[])
{
BFun b;
AFun a;
a.callback = boost::bind<&BFun::BindTestFun, b, _1>;
a.run();

return 0;
}

主要思想是 BFun类实现具体回调方法.. AFun类通过CallBack调用回调...
可是编译有编译错误:
Error 1 error C2563: mismatch in formal parameter list \testboost.cpp 39 1 testBoost
Error 2 error C2568: '=' : unable to resolve function overload \testboost.cpp 39 1 testBoost
错误1: 参数列表不匹配.....
错误2: 无法重载resolve function....
求教....



...全文
175 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
kuai2361425 2015-02-11
  • 打赏
  • 举报
回复
谢谢各位...问题已经解决了.. 主要问题不在语法错误... 贴上 正确代码... 主要是boost::shared_ptr 与 this 指针的转换问题...
// testBoost.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

class AFun: public boost::enable_shared_from_this<AFun>
{
public:
	//boost::function<void(boost::shared_ptr<AFun>&)>  QueryCallBack;
	typedef boost::function<void( boost::shared_ptr<AFun>&)>  BTCALLBACK;
	BTCALLBACK	callback;
	void print(){
		std::cout<<"GGGGGGGGGGGGGGGGGGGGGGGGGGGG"<<std::endl;
	}
	void run(){
		boost::shared_ptr<AFun> aFun = this->shared_from_this();
		callback(aFun);
	}
	
};
//typedef boost::function<void( boost::shared_ptr<AFun>&)>  BTCALLBACK;
class BFun
{
public:
	void BindTestFun(boost::shared_ptr<AFun>& aFun){
		aFun->print();
	}
	void run(){
		boost::shared_ptr<AFun> aptr(new AFun());
		aptr->callback = boost::bind(&BFun::BindTestFun, *this, _1);
		aptr->run();
	}
};



int _tmain(int argc, _TCHAR* argv[])
{	
	BFun b;
	b.run();
	return 0;
}

fly_dragon_fly 2015-02-11
  • 打赏
  • 举报
回复
boost::bind(&BFun::BindTestFun, &b, _1); bind是个函数调用,是圆括号,不是尖括号,另外标准库里面已经有bind了
lincolnandlinda 2015-02-11
  • 打赏
  • 举报
回复
a.callback = boost::bind<&BFun::BindTestFun, &b, _1>;

64,661

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧