请教:关于boost::bind的用法

cabinriver 2012-10-29 03:27:11



#include <boost/bind.hpp>
#include <iostream>

using namespace std;

class TEST{
public:
void Print(int ival)
{
cout<<"执行打印: "<<ival<<endl;
}
};

int main(int argc, char **argv)
{
TEST test;
boost::bind(&TEST::Print, test, _1)(1);

int tt = 0;
tt =1;
}




//怎么用bind,什么时候用?什么地方用?
//在一般的用法中没有发现bind的任何优点
//而且从上面的代码来看,远远没有直接用
//test.Print(1)用起来方便。

//请高手指点....
...全文
220 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qingcairousi 2012-10-29
  • 打赏
  • 举报
回复
好吧,上面的代码犯了不少错。
bind就是给你统一接口用的。
你有个回调,回调的参数已经规定好了,而你又有个现有的接口,参数和回调不一致,这个时候可以用bind来统一接口。
qingcairousi 2012-10-29
  • 打赏
  • 举报
回复

#include <boost/bind.hpp>
#include <iostream>

using namespace std;

class TEST{
public:
void Print(int ival, int iVal2)
{
cout<<"执行打印: " << ival << "," << iVal2 <<endl;
}
};

template <typename Printer>
void print42(Printer& printer)
{
printer(42);
}

int main(int argc, char **argv)
{
TEST test;
auto printer = boost::bind(&TEST::Print, test, _1)(1);
print42(printer);
}



这是Adapter模式。

其实随着c++ 11的推出,各种bind我觉得没啥太大意义了,用lambda就能干这些bind,还更优雅更灵活。

64,646

社区成员

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

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