C++11新特性,bind,基於對象

來源:互聯網
上載者:User

標籤:main   原函數   ios   實體   nis   類型   border   tab   lru   

function/bind:
std::function: ?std::function<R(T1, T2, ..., TN)> 
?這是一個模板實現的函數對象類,它可以封裝其它任意的函數對象,而被封裝的函數對象具有類型為T1,T2,…,TN的參數,其傳回值為R類型
?function 對象的最大用處在於實現函數回調

bind: ?bind是這樣一種機制,它可以預先把指定可調用實體的某些參數綁定到已有的變數,產生一個新的可調用實體 ?綁定的參數的個數不受限制 ?綁定的具體哪些參數也不受限制,由使用者指定 ?bind預先綁定的參數需要傳具體的變數或值進去,是pass-by-value(值傳遞)的 ?對於不事先綁定的參數,需要傳std::placeholders進去,從_1開始,依次遞增 ?bind的傳回值是可調用實體,可以直接賦給std::function對象

物件導向  vs  基於對象: ?物件導向的三大特點(封裝,繼承,多態)缺一不可。 ?通常“基於對象”是使用對象,但是並不利用現有的對象模板產生新的物件類型,繼而產生新的對象,即“基於對象”沒有繼承的特點。 ?“物件導向”和“基於對象”都實現了“封裝”的概念,但是物件導向實現了“繼承和多態”,而“基於對象”沒有實現這些。
                                                               繼承(物件導向)  vs  組合(基於對象)

// bind 返回一個新的可調用實體 // function 對象實現函數回調 #include<iostream> #include<functional> using namespace std; using std::function; //using std::placeholders;  // namespace ‘std::placeholders’ not allowed in using-declaration using namespace std::placeholders; int func(int x,int y) {         return x+y; } class A {         public:                 int func(int x,int y)                 {                         return x+y;                 } };
int main() {         // function<int(int,int)> test1  = bind(func,10,placeholders::_1); // 只有一個預留位置,意思傳參只要傳一個,所以形參不能是兩個,和原函數沒關係         function<int(int)> test1  = bind(func,10,placeholders::_1);         cout<<test1(20)<<endl;
        A a;         function<int(int)> test2 = bind(&A::func,&a,30,_1);   // 前面聲明,就不用寫placeholders         cout<<test2(40)<<endl;
        function<int(int,int)> test3 = func;         cout<<test3(10,20)<<endl;
        //function<int(const A&,int,int)> test4 = &A::func;           function<int(A&,int,int)> test4 = &A::func;   // 今天腦子犯抽,const成員對象只能調用const修飾的成員函數         cout<<test4(a,10,20)<<endl;         return 0; }





C++11新特性,bind,基於對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.