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的那些不是占位符的参数被拷贝到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 }
参考资料
C++11 中的function和bind、lambda用法
原文:https://www.cnblogs.com/sunbines/p/10567541.html