boost库在工作(13)绑定器与函数对象之一

来源:互联网 发布:linux下安装pyqt4 编辑:程序博客网 时间:2024/06/06 08:27
在STL模板库里提供两个绑定器:bind1st和bind2nd,这两个绑定器只支持两个参数,如果是两个以上的参数,就无能为力了。下面先来看看这两个绑定器的使用例子,如下:
// boost_008.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>#include <functional>#include <boost/bind.hpp>void Fun(int x, int y){std::cout << "Fun:" << x - y << std::endl;}//使用bind1stvoid TestCase1(void){std::cout << "std::bind1st(std::ptr_fun(Fun), 10)(1)" << std::endl;std::bind1st(std::ptr_fun(Fun), 10)(1);std::cout << "std::bind2nd(std::ptr_fun(Fun), 10)(1)" << std::endl;std::bind2nd(std::ptr_fun(Fun), 10)(1);}int _tmain(int argc, _TCHAR* argv[]){TestCase1();system("PAUSE");return 0;}

运行这个例子,结果输出如下:

std::bind1st(std::ptr_fun(Fun), 10)(1)

Fun:9

std::bind2nd(std::ptr_fun(Fun), 10)(1)

Fun:-9

请按任意键继续. . .

 

在例子里,这行代码:

std::bind1st(std::ptr_fun(Fun), 10)(1);

std::bind1st是绑定器;std::ptr_fun是获取函数的指针,并转换为合适的指针给绑定器使用;10是需要绑定的参数;1是传送给绑定后的函数的参数。因为函数void Fun(int x, int y)有两个参数,经过绑定器std::bind1st绑定第一个参数后,转换出来的函数对象只需要输入一个参数就可以了。由此可见,绑定器可以把两个参数的函数指针转换为只有一个参数的函数对象。std::bind1st和std::bind2nd的区别是选择绑定两个参数的那一个参数上。从上面的例子可以看到,使用std::bind1st是绑定到第一个参数,函数的调用就相当于Fun(10,1),所以(x-y)运算结果是9。而std::bind2nd是绑定到第二个参数,函数的调用相当于Fun(1,10),所以(x-y)运算结果是-9。

细心的同学或许发现一个特性,std::bind1st和std::bind2nd传入的参数是一样的大小和顺序,但传送给Fun函数会不一样,这样特性就叫做参数重排,利用这个特性可以让同样小于判断的函数,同样可以用于大于的判断上。
原创粉丝点击