lambda,std::function, 函数对象,bind的使用备忘
Demo备忘,占坑
#include <iostream> #include <functional> #include <vector> using namespace std; using namespace std::placeholders; const static int T_NUM = 10; bool test_functional(const std::function<bool(int)> &f, int t) { return f(t); } struct test_struct { public: bool operator()(int t) { if (t > T_NUM) { buffer.push_back(t); } return true; } public: std::vector<int> buffer; }; int test_binder_functional(int a, int b) { return a+b; } int test_binder_function2(int &a) { return ++a; } class BindTestClass { public: BindTestClass(std::string name="") : name_(name) {} void Print(std::string prefix="") { std::cout << prefix << " " << name_ << std::endl;} private: std::string name_ {""}; }; int main() { //函数对象 test_struct t; test_functional(t,9); test_functional(t,10); test_functional(t,11); test_functional(t,12); //打印不出任何东西,函数对象到 std::function存在隐式转换 for(auto it=t.buffer.begin(); it != t.buffer.end(); it++) { std::cout << *it << std::endl; } //------------------------------- // lambda std::vector<int> buffer; std::function<bool(int)> test_f = [&buffer](int t)->bool { if (t > T_NUM) { buffer.push_back(t); } }; test_functional(test_f,9); test_functional(test_f,10); test_functional(test_f,11); test_functional(test_f,12); // 打印 11,12 for(auto it=buffer.begin(); it != buffer.end(); it++) { std::cout << *it << std::endl; } //-------------------------------- // bind的使用 // bind 固定某个参数 auto bind_test_f = std::bind(test_binder_functional,_1,10); std::cout << bind_test_f(10) << std::endl; // bind auto divide_f = std::bind(std::divides<double>(), _1, 7); std::cout << divide_f(49) << std::endl; // nesting bind 嵌套bind auto time3_f = std::bind(std::multiplies<double>(), _1, std::bind(std::multiplies<double>(),_1,_1)); std::cout << time3_f(10) << std::endl; std::cout << time3_f(20) << std::endl; // bind_num_v will not change 引用bind需要加 ref 修饰 int bind_num_v = 10; auto bind_num_f = std::bind(test_binder_function2,bind_num_v); bind_num_f(); std::cout << bind_num_v << std::endl; // bind_num_v will change auto bind_num_f_c = std::bind(test_binder_function2,ref(bind_num_v)); bind_num_f_c(); std::cout << bind_num_v << std::endl; // bind class function 绑定类成员函数 auto class_bind_f = std::bind(&BindTestClass::Print, _1, "my name is:"); BindTestClass bindc("nicolas"); class_bind_f(bindc); return 0; }