function是函数、函数对象、函数指针、和成员函数的包装器,可以容纳任何类型的函数对象,函数指针,引用函数,成员函数的指针
普通函数
#include <functional> void print_num(int i) { cout << "i" << endl; } function<void(int)> f_display = print_num; f_display(-9); function<void()> f_display_42 = [](){ print_num(42); }; f_display_42(); function<void()> f_display_32337 = bind(print_num, 32337); //对bind不明白参考bind f_display_32337();
类成员函数
#include <functional> stuct Foo { Foo(int num) : num_(num) {} void print_add(int i) const { cout << num_ + i << endl;} int num_; }; function<void(const Foo&, int)> f_add_display = &Foo::print_add; const Foo foo(314159); f_add_display(foo, 1); function<void(int)> f_add_display2 = bind(&Foo::print_add, foo, placeholders::_1); f_add_display2(2);
一个实际的应用:
1 #include <functional> 2 #include <iostream> 3 4 using namespace std; 5 6 class Scope { 7 public: 8 explicit Scope(function<void()> o) : 9 on_exit_(o) {} 10 ~Scope() { on_exit_(); } 11 private: 12 function<void()> on_exit_; 13 }; 14 15 int main() 16 { 17 Scope scope([]() { cout << "close" << endl; }); 18 }
输出结果: close
转载于:https://www.cnblogs.com/457220157-FTD/p/4019164.html