成員函數的函數配接器

來源:互聯網
上載者:User

標籤:c++   函數配接器   

在STL標準庫中除了提供常規的函數配接器外,還提供了兩個針對成員函數的函數配接器,其主要功能是通過這些配接器,你可以針對每一個元素直接去調用其成員函數。

這樣的成員函數配接器有兩個,分別是:

mem_fun_ref(op)調用對象的成員函數op

mem_fun(op)調用對象指標的成員函數op

這兩個函數配接器都是去調用對象中的成員函數op,對於這兩個成員函數,以前是只能調用對象的const成員函數,但現在的情況好像有所改變,對所有的成員函數都可以調用了。

具體的樣本如下:

#include<iostream>#include<functional>#include<deque>#include<algorithm>#include<iterator>using namespace std;class A{public:A(int b):a(b){}~A(){}void mfun(){ostream_iterator<int>(cout,"--") = ++a;}private:int a;};int main(){deque<A>de;for(int i = 0;i<5;i++)de.push_back(A(i));for_each(de.begin(),de.end(),mem_fun_ref(&A::mfun));cout<<endl;deque<A*>de2;for(int i = 0;i<5;i++)de2.push_back(new A(i));for_each(de2.begin(),de2.end(),mem_fun(&A::mfun));/*1--2--3--4--5--1--2--3--4--5--請按任意鍵繼續. . .*/}

使用注意:

一、通過該類配接器調用的成員函數必須要在對象的類型中存在。

二、這兩個配接器的參數都必須是傳遞該類型中成員函數的位移量,不能直接傳遞函數名。

聯繫我們

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