標籤:blog int 功能 namespace 臨時對象 div 指標 函數指標 ++
1.bind()
函數對象:可以以函數方式與()結合使用的任意對象,包括 function 仿函數、函數名、函數指標、含有()操作符的類對象。
function是一組函數對象封裝類的模版,(又叫防函數)實現一個泛型的回調機制,function< int( int, int)>形式,可調用的對象普通函數、函數指標、lanmbda運算式、函數對象和類的成員函數等。
int add(int i, int j){ return a + b;}auto mod = [](int a, int b){ return a%b;}struct divide{ int operator()(int i, int j){ return i/j; }};function<int(int, int)> func1 = add;function<int(int, int)> func2 = mod;function<int(int, int)> func3 = divide;func1(1, 2);int a = func2(1, 2);func3(1, 2);
//bindtemplate <class Fn, class... Args> /* unspecified */ bind (Fn&& fn, Args&&... args);
bind返回一個和Fn功能相同,但參數是Args(已經填好了,調用時不用傳參了)和預留位置的函數對象,如果Fn是成員函數,則傳回值第一個參數this指標。
struct integer{ int i; integer(int i):i(i){} void incr_by(int j) {i += j;}};integer x(0);integer* y = &x;using namespace std::placeholders;auto f0 = bind(&integer::incr_by, _1, _2);f0(x, 2); //x.incr_by(2); x.i = 2;f0(y,2);//y->incr_by(2); x.i = 4;auto f1 = bind(&integer::incr_by, x, _1);f1(2); //這裡x是值傳遞,調用的是一個臨時對象的incr_by函數,x的i不改變。auto f2 = bind(&integer::incr_by, ref(x), _1);f2(2);//引用,x改變了,x.i = 6;auto f3 = bind(&integer::incr_by, &x, _1);f2(2);//指標,x改變了,x.i = 8;
C++ 11