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 }

参考资料

 

转载于:https://www.cnblogs.com/sunbines/p/10567541.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值