[转] c++11 bind和function

[转自 https://blog.csdn.net/fjb2080/article/details/7527715]html

[转自 https://www.cnblogs.com/lidabo/p/7266885.html]ios

[转自 https://www.jianshu.com/p/f191e88dcc80]app

1.std::bind

标准库函数bind()和function()定义于头文件中(该头文件还包括许多其余函数对象),用于处理函数及函数参数。bind()接受一个函数(或者函数对象,或者任何你能够经过”(…)”符号调用的事物),生成一个其有某一个或多个函数参数被“绑定”或从新组织的函数对象。(译注:顾名思义,bind()函数的意义就像它的函数名同样,是用来绑定函数调用的某些参数的。)例如:ide

1 #include<iostream>
2 using namespace std;
3 int  main()
4 {
5         auto func = [] () {cout << "hello world"; };
6           
7         func();//now call the function
8 }        

参数的绑定一般称为”Currying”(译注:Currying—“烹制咖喱烧菜”,此处意指对函数或函数对象进行加工修饰操做), “_1″是一个占位符对象,用于表示当函数f经过函数ff进行调用时,函数ff的第一个参数在函数f的参数列表中的位置。第一个参数称为”_1″, 第二个参数为”_2″,依此类推。例如:函数

1 int f(int, char, double);
2 auto frev =bind(f, _3, _2, _1); //翻转参数顺序
3 int x = frev(1.2, 'c',7); //f(7, 'c'.1.2);

此处,auto关键字节约了咱们去推断bind返回的结果类型的工做。ui

咱们没法使用bind()绑定一个重载函数的参数,咱们必须显式地指出须要绑定的重载函数的版本:this

1 int g(int);
2 double g(double);
3 
4 auto g1= bind(g,_1); //错误,调用哪个g()?
5 //正确,可是至关丑陋
6 auto g2=bind( ( double(*) (double))g, _1);

bind()有两种版本:一个如上所述,另外一个则是“历史遗留”的版本:你能够显式地描述返回类型。例如:spa

1         auto f2 = bind<int> (f, 7, ‘c’, _1);      // 显式返回类型
2 
3         int x = f2(1.2);                    // f(7, ‘c’, 1.2);

第二种形式的存在是必要的,而且由于第一个版本((?) “and for a user simplest “,此处请参考原文))没法在C++98中实现。因此第二个版本已经被普遍使用。.net

 

1.1 std::bind绑定普通函数

double my_divide (double x, double y) {return x/y;} auto fn_half = std::bind (my_divide,_1,2); std::cout << fn_half(10) << '\n'; // 5 
  • bind的第一个参数是函数名,普通函数作实参时,会隐式转换成函数指针。所以std::bind (my_divide,_1,2)等价于std::bind (&my_divide,_1,2);
  • _1表示占位符,位于<functional>中,std::placeholders::_1;

1.2 std::bind绑定一个成员函数

struct Foo { void print_sum(int n1, int n2) { std::cout << n1+n2 << '\n'; } int data = 10; }; int main() { Foo foo; auto f = std::bind(&Foo::print_sum, &foo, 95, std::placeholders::_1); f(5); // 100 } 
  • bind绑定类成员函数时,第一个参数表示对象的成员函数的指针,第二个参数表示对象的地址。
  • 必须显示的指定&Foo::print_sum,由于编译器不会将对象的成员函数隐式转换成函数指针,因此必须在Foo::print_sum前添加&;
  • 使用对象成员函数的指针时,必需要知道该指针属于哪一个对象,所以第二个参数为对象的地址 &foo;

1.3 绑定一个引用参数

默认状况下,bind的那些不是占位符的参数被拷贝到bind返回的可调用对象中。可是,与lambda相似,有时对有些绑定的参数但愿以引用的方式传递,或是要绑定参数的类型没法拷贝。指针

#include <iostream> #include <functional> #include <vector> #include <algorithm> #include <sstream> using namespace std::placeholders; using namespace std; ostream & print(ostream &os, const string& s, char c) { os << s << c; return os; } int main() { vector<string> words{"helo", "world", "this", "is", "C++11"}; ostringstream os; char c = ' '; for_each(words.begin(), words.end(), [&os, c](const string & s){os << s << c;} ); cout << os.str() << endl; ostringstream os1; // ostream不能拷贝,若但愿传递给bind一个对象, // 而不拷贝它,就必须使用标准库提供的ref函数 for_each(words.begin(), words.end(), bind(print, ref(os1), _1, c)); cout << os1.str() << endl; } 

1.4. 指向成员函数的指针

经过下面的例子,熟悉一下指向成员函数的指针的定义方法。

#include <iostream> struct Foo { int value; void f() { std::cout << "f(" << this->value << ")\n"; } void g() { std::cout << "g(" << this->value << ")\n"; } }; void apply(Foo* foo1, Foo* foo2, void (Foo::*fun)()) { (foo1->*fun)(); // call fun on the object foo1 (foo2->*fun)(); // call fun on the object foo2 } int main() { Foo foo1{1}; Foo foo2{2}; apply(&foo1, &foo2, &Foo::f); apply(&foo1, &foo2, &Foo::g); } 
  • 成员函数指针的定义:void (Foo::*fun)(),调用是传递的实参: &Foo::f;
  • fun为类成员函数指针,因此调用是要经过解引用的方式获取成员函数*fun,即(foo1->*fun)();

 

2. std::function

function是一个拥有任何能够以”(…)”符号进行调用的值的类型。特别地,bind的返回结果能够赋值给function类型。function十分易于使用。(译注:更直观地,能够把function当作是一种表示函数的数据类型,就像函数对象同样。只不过普通的数据类型表示的是数据,function表示的是函数这个抽象概念。)例如:

 1         // 构造一个函数对象,
 2 
 3         // 它能表示的是一个返回值为float,
 4 
 5         // 两个参数为int,int的函数
 6 
 7         function<float (int x, int y)> f;   
 8 
 9         // 构造一个可使用"()"进行调用的函数对象类型
10 
11         struct int_div {
12 
13                 float operator() (int x, int y) const
14 
15                      { return ((float)x)/y; };
16         };
17         f = int_div();                    // 赋值
18         cout<< f(5,3) <<endl;  // 经过函数对象进行调用
19         std::accumulate(b, e, 1, f);        // 完美传递

成员函数可被看作是带有额外参数的自由函数:

 1         struct X {
 3                 int foo(int); 
 5         };
 9         // 所谓的额外参数,
11         // 就是成员函数默认的第一个参数,
13         // 也就是指向调用成员函数的对象的this指针 
15         function<int (X*, int)> f; 
17         f = &X::foo;            // 指向成员函数
21         X x;
23         int v = f(&x, 5);  // 在对象x上用参数5调用X::foo()
25         function<int (int)> ff = std::bind(f, &x, _1);    // f的第一个参数是&x
27         v = ff(5);                // 调用x.foo(5)

function对于回调函数、将操做做为参数传递等十分有用。它能够看作是C++98标准库中函数对象mem_fun_t, pointer_to_unary_function等的替代品。一样的,bind()也能够被看作是bind1st()和bind2nd()的替代品,固然比他们更强大更灵活。

 

 

function是一组函数对象包装类的模板,实现了一个泛型的回调机制。

引入头文件

#include <functional>
using namespace std;
using namespace std::placeholders;  //bind的时候会用`

参考:http://www.cnblogs.com/hujian/archive/2012/12/07/2807605.html

fuction  bind:http://blog.csdn.net/fjb2080/article/details/7527715

咱们能够调用的对象有不少,好比普通函数、函数指针、lambda表达式、函数对象和类的成员函数等。

无论采用哪一种方式,主要调用形式同样(返回值类型、传递给调用的实参类型),咱们就可使用同一种形式来调用。

这个时候就能够用到function模板,它给予咱们在调用的方式上更大的弹性。

请看一下三种不一样的函数定义:

1 int add(int a, int b){//普通函数 2     return a+b;
3 }
4 auto mod=[](int a, int b){return a%b;}; //lambda 函数
5 struct divide{ //函数对象 6 int operator()(int m, int n){ 7 return m/n; 8 } 9 };

这三种均可以使用同一种调用形式,int(int, int),调用方式以下:

1  function<int(int,int)> func1= add;
2  function<int(int,int)> func2= divide();
3  function<int(int,int)> func3= mod;
4  cout<<func1(5, 6)<<endl;
5  cout<<func2(5, 6)<<endl;
6  cout<<func3(5, 6)<<endl;

学会了使用function,能够继续以下进行抽象定义,不一样类型采用相同的调用方法:

1  map<string,function<int(int, int)>> funs =
2     {
3         {"+", add},
4         {"-", std::minus<int>()},//标准库的函数,参数为两个整数,能够参考前一篇博客
5         {"/", divide()},//类成员函数
6         {"*", [](int i,int j){return i*j;}},//lambda表达式
7         {"%", mod},
8     };
9     funs["+"](4,6);

以上就是function的简单使用。下面是从另外一篇博客转载的,使用function的引用来保存函数对象。考虑下面代码:

 1 class CAdd
 2 
 3 {
 4 public:
 5     CAdd():m_nSum(0){NULL;}
 6     int operator()(int i)
 7     {
 8         m_nSum += i;
 9         return m_nSum;
10     }
11     int Sum() const
12     {
13         return m_nSum;
14     }
15 private:
16     int m_nSum;
17 };
18 int main(int argc, const char * argv[])
19 {
20     CAdd cAdd;
21     function<int(int)> funcAdd1 = cAdd;
22     function<int(int)> funcAdd2 = cAdd;
23     cout<<funcAdd1(10)<<endl;
24     cout<<funcAdd2(10)<<endl;
25     cout<<cAdd.Sum()<<endl;
26      return 0;
27 }

上面的输出结果是 10 10 0。咱们将同一个函数对象赋值给了两个function,而后分别调用这两个function,但函数中的成员变量的值没有保存,问题在哪里?由于function的缺省行为是拷贝一份传递给它的函数对象,因而f1,f2中保存的都是cAdd对象的拷贝。
C++11提供了ref和cref函数来提供对象的引用和常引用的包装。要是function可以正确保存函数对象的状态,能够以下修改代码:

1     function<int(int)> funcAdd3 = ref(cAdd);
2     function<int(int)> funcAdd4 = ref(cAdd);
3     cout<<funcAdd3(10)<<endl;
4     cout<<funcAdd4(10)<<endl;
5     cout<<cAdd.Sum()<<endl;

另外,两个function之间赋值时,若是源function保存的是函数对象的拷贝,则目标function保存的也是函数对象的拷贝。若是源function保存的是对函数对象的引用,则目标function保存的也是函数对象的引用。

相关文章
相关标签/搜索