C++ 11

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.