boost学习之bind
来源:互联网 发布:宜州市一中网络硬盘 编辑:程序博客网 时间:2024/05/16 16:05
要点:
1 是标准库中bind1st和bind2st的扩展,功能更强大
2 他是一个创建函数对象的工具,而函数对象时标准库的算法需要的,所以bind提供了方便创建函数对象的功能
3 使用bind的代码更简洁,易懂,较标准库的mem_fun,mem_fun_ref等好用
4 bind的占位符_1,_2...对普通函数最多有9个,对于成员函数仅支持8个,第一个参数是类的this指针
5 bind的本质是通过模板的手法创建一个函数对象,然后使用时调用函数对象的operator()操作符
6 基本用法:
class some_class {public:
typedef void result_type;
void print_string(const std::string& s)const
{
std::cout << s << '\n';
}
};
void print_string(const std::string s)
{
std::cout << s << '\n';
}
(boost::bind(&print_string,_1))("Hello func!");
some_class sc;
(boost::bind(&some_class::print_string,_1,_2))(sc,"Hello member!");//_1对应sc,_2对应"Hello member!"
7 bind在排序方面应用
std::vector<personal_info> vec;
vec.push_back(personal_info("Little","John",60));
vec.push_back(personal_info("Friar", "Tuck",50));
vec.push_back(personal_info("Robin", "Hood",40));
std::sort( vec.begin(),vec.end(),
boost::bind(std::less<unsigned int>(),
boost::bind(&personal_info::age_,_1),
boost::bind(&personal_info::age_,_2))
);
理解这个问题关键在于对下面表达式的理解:
unsigned int age_ = boost::bind(&personal_info::age_,personal_info("Little","John",年龄))();
所以上面表达式: boost::bind(&personal_info::age_,_1)等价于上面表达式,其中_1代表的是传递给boost::bind()(std::less....)(arg1,arg2)中的arg1,即personal_info类 型 的 引用,boost::bind(&personal_info::age_,_2)情况是一样的;
然后,因为boost::bind(&personal_info::age_,_1)就是age,所以排序的一次中间结果会是如下这样:
bool c = boost::bind(std::less<unsigned int>(),60,50)(personal_info("Little","John",60),personal_info("Little","John",50));
所以最终能够正确排序;
8 bind可以表达一个区间的概念
std::vector<int>::iterator int_it=
std::find_if(ints.begin(),ints.end(),
boost::bind<bool>(
std::logical_and<bool>(),
boost::bind<bool>(std::greater<int>(),_1,5),
boost::bind<bool>(std::less_equal<int>(),_1,10)));
9 bind其他用法
typedef std::map<std::string,std::vector<int> > map_type;
map_type m;
m["Strange?"].push_back(1);
m["Strange?"].push_back(2);
m["Strange?"].push_back(3);
m["Weird?"].push_back(4);
m["Weird?"].push_back(5);
std::for_each(m.begin(),m.end(),
boost::bind(print_size(),boost::ref(std::cout),_1));
10 占位符
每个占位符对应一个参数;
class some_class {
public:
void print_string(const std::string s) {
std::cout << s << '\n';
}
}
下面三种形式都对:
(boost::bind(&some_class::print_string,_1,_2))
(sc,"Hello member!");//直观用法
(boost::bind(&some_class::print_string,some_class(),_1))
("Hello member!");//
(boost::bind(&some_class::print_string,
some_class(),"Hello member!"))();
总结,bind确实很好用;
- 【boost学习】之boost::bind
- boost学习之bind
- Boost学习笔记之bind
- C++学习 boost学习之-bind
- Boost学习笔记之五 bind
- Boost库之bind适配器学习
- 【03】 Boost库学习笔记之Bind
- Boost学习笔记-bind
- boost::bind 学习
- boost 线程学习bind
- Boost::bind学习
- 2.Boost之bind
- Boost库之bind
- boost库学习之bind的常见用法
- Boost::Bind 库 之bind(1)
- boost::bind实现原理学习
- boost之bind源码剖析
- boost之bind的使用
- 独特的ARM
- 第一个驱动程序
- 学习笔记(十二)
- 修改vsftpd的默认根目录
- 大端模式和小端模式
- boost学习之bind
- 死锁
- redhat gcc g++安装
- poj 2187 Beauty Contest 凸包最长直径
- VIM配置文件
- Android OpenGL ES 开发教程(4):OpenGL ES API 命名习惯
- XML 编码格式
- 服务器通过Servlet接收文件
- 英语词汇3