要傳入?yún)?shù)給global function ,需要使用 ptr_fun() 這個(gè) function adapter 將global function 轉(zhuǎn)成function object , 然后再用bind2nd() 將參數(shù)bind成一個(gè)function object。(這句話好拗口)
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>struct Foo{Foo(int num):num_(num){};void print_add(int i)const {std::cout << num_ + i << std::endl;}int num_;
};
void print_num(int i){std::cout << i << '\n';
}
struct print_Num{void operator()(int i){std::cout << i << '\n';}
};int main(){//store a free functionstd::function<void(int)>f_display = print_num;f_display(-9);//strore a lambdastd::function<void()> f_display_42 = [](){ print_num(43);};f_display_42();//store the result of a call to std::bindstd::function<void()>f_display_31337 = std::bind(print_num,31337);f_display_31337();//store a call to a member functionstd::function<void(const Foo&,int)>f_add_display = &Foo::print_add;const Foo foo(300000);f_add_display(foo,1);//store a call to a member function and objectusing std::placeholders::_1;std::function<void(int)>f_add_display2 = std::bind(&Foo::print_add,foo,_1);f_add_display2(2);//store a call to a member function and object ptrstd::function<void(int)>f_add_display3 = std::bind(&Foo::print_add,&foo,_1);f_add_display3(3);//store a call to a function objectstd::function<void(int)>f_display_obj = print_Num();f_display_obj(18);
}
參考鏈接
bind1st bind2nd的使用_simahao的專欄-CSDN博客_bind2nd
C++ STL std::ptr_fun() 函數(shù)說(shuō)明 - 簡(jiǎn)書(shū)