C++11 中的function和bind、lambda用法

时间:2019-03-20
本文章向大家介绍C++11 中的function和bind、lambda用法,主要包括C++11 中的function和bind、lambda用法使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

std::function

1. std::bind绑定一个成员函数

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

3.3 绑定一个引用参数

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

 1 #include <iostream>
 2 #include <functional>
 3 #include <vector>
 4 #include <algorithm>
 5 #include <sstream>
 6 using namespace std::placeholders;
 7 using namespace std;
 8 
 9 ostream& print(ostream &os, const string& s, char c)
10 {
11     os << s << c;
12     return os;
13 }
14 
15 int main()
16 {
17     vector<string> words{ "helo", "world", "this", "is", "C++11" };
18     ostringstream os;
19     char c = ' ';
20     for_each(words.begin(), words.end(),
21         [&os, c](const string & s) {os << s << c; });
22     cout << os.str() << endl;
23 
24     ostringstream os1;
25     // ostream不能拷贝,若希望传递给bind一个对象,
26     // 而不拷贝它,就必须使用标准库提供的ref函数
27     for_each(words.begin(), words.end(),
28         bind(print, ref(os1), _1, c));
29     cout << os1.str() << endl;
30 }

参考资料