---
title: "Boost::bind"
author: "lunan"
date: "2011-10-31T00:07:48Z"
tags: ["bind", "boost"]
categories: ["编程语言"]
slug: "boost-bind"
draft: false
lastmod: "2011-11-05T15:04:50Z"
id: 1223183
url: "https://lunan.iteye.com/blog/1223183"
---

/* Boost::bind 1） bind1st,bind2st函数绑定器，把二元函数对象变为一元函数对象。 2） mem\_fun,把成员函数变为函数对象。 3） fun\_ptr，把一般的全局函数变为函数对象。 4） boost::bind(),统一的接口实现以上所有的功能。 注意 1) 现在的类库最多可以支持9个参数。 2）在绑定一个成员函数时，bind 表达式的第一个参数必须是成员函数所在类的实例！理解这个规则的最容易的方法是，这个显式的参数将取替隐式的 this ，被传递给所有的非静态成员函数。细心的读者将会留意到，实际上这意味着对于成员函数的绑定器来说，只能支持八个参数，因为第一个要用于传递实际的对象。 3）当我们传递某种类型的实例给一个 bind 表达式时，它将被复制，除非我们显式地告诉 bind 不要复制它。要避免复制，我们必须告诉bind 我们想传递引用而不是它所假定的传值。我们要用 boost::ref 和 boost::cref (分别用于引用和 const 引用)来做到这一点，它们也是Boost.Bind 库的一部分。还有一种避免复制的方法；就是通过指针来传递参数而不是通过值来传递。 4） 通过 Boost.Bind, 你可以象使用非虚拟函数一样使用虚拟函数，即把它绑定到最先声明该成员函数为虚拟的基类的那个虚拟函数上。这个绑定器就可以用于所有的派生类。如果你绑定到其它派生类，你就限制了可以使用这个绑定器的类。 5）bind还可以绑定成员变量。 \*/ #include "stdafx.h" #include #include #include #include #include #include "boost/bind.hpp" using namespace std; struct point { int x,y; point(int a=0,int b=0):x(a),y(b){} void print(){ cout &lt;&lt; "(" &lt;&lt; x &lt;&lt; "," &lt;&lt; y &lt;&lt; ")\\n"; } void setX(int a){ cout &lt;&lt; "setX:" &lt;&lt; a &lt;&lt; endl; } void setXY(int x,int y){ cout &lt;&lt; "setX:" &lt;&lt; x &lt;&lt; ",setY:" &lt;&lt; y &lt;&lt; endl; } void setXYZ(int x,int y,int z){ cout &lt;&lt; "setX:" &lt;&lt; x &lt;&lt; ",setY:" &lt;&lt; y &lt;&lt; "setZ:" &lt;&lt; z &lt;&lt; endl; } }; int main(void){ std::vector ints; ints.push\_back(7); ints.push\_back(4); ints.push\_back(12); ints.push\_back(10); int count=std::count\_if(ints.begin(), ints.end(), boost::bind(std::logical\_and(), boost::bind(std::greater(),\_1,5), boost::bind(std::less\_equal(),\_1,10)) ); std::cout &lt;&lt; count &lt;&lt; '\\n'; std::vector::iterator int\_it=std::find\_if(ints.begin(),ints.end(), boost::bind(std::logical\_and(), boost::bind(std::greater(),\_1,5), boost::bind(std::less\_equal(),\_1,10)) ); if (int\_it!=ints.end()) { std::cout &lt;&lt; \*int\_it &lt;&lt; '\\n';} point p1,p2; bind(&point::setX,p1,\_1)(10); bind(&point::setXY,p1,\_1,\_2)(10,20); bind(&point::setXYZ,p2,\_1,\_2,\_3)(10,20,30); vector v(2); //for\_each的时候只需要\_1就可以了 for\_each(v.begin(),v.end(),bind(&point::print,\_1)); for\_each(v.begin(),v.end(),bind(&point::setX,\_1,10)); for\_each(v.begin(),v.end(),bind(&point::setXY,\_1,10,20)); for\_each(v.begin(),v.end(),bind(&point::setXYZ,\_1,10,20,30)); return 0; }