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

在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;
}
//使用bind1st

void 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函数会不一样,这样特性就叫做参数重排,利用这个特性可以让同样小于判断的函数,同样可以用于大于的判断上。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值