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确实很好用;