共用方式為


mem_fun 函式

當使用指標引數初始化時,helper 樣板函式用來為成員函式建構函式物件配接器。

template<class Result, class Type> 
   mem_fun_t<Result, Type> mem_fun ( 
      Result(Type::* _Pm )( )  
); 

template<class Result, class Type, class Arg> 
   mem_fun1_t<Result, Type, Arg> mem_fun( 
      Result (Type::* _Pm )( Arg )  
); 

template<class Result, class Type> 
   const_mem_fun_t<Result, Type> 
      mem_fun(Result (Type::* _Pm )( ) const  
); 

template<class Result, class Type, class Arg> 
   const_mem_fun1_t<Result, Type, Arg> 
      mem_fun(Result (Type::* _Pm )( Arg ) const  
);

參數

  • _Pm
    對類別要轉換的 [型別] 的成員函式的指標函式物件。

傳回值

型別為 mem_fun_tmem_fun1_tconstnon_const 函式物件。

範例

// functional_mem_fun.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>

using namespace std;

class StoreVals   
{
    int val;
public:
    StoreVals() { val = 0; }
    StoreVals(int j) { val = j; }

    bool display() { cout << val << " "; return true; }
    int squareval() { val *= val; return val; }
    int lessconst(int k) {val -= k; return val; }
};

int main( )
{
    vector<StoreVals *> v1;

    StoreVals sv1(5);
    v1.push_back(&sv1);
    StoreVals sv2(10);
    v1.push_back(&sv2);
    StoreVals sv3(15);
    v1.push_back(&sv3);
    StoreVals sv4(20);
    v1.push_back(&sv4);
    StoreVals sv5(25);
    v1.push_back(&sv5);

    cout << "The original values stored are: " ;
    for_each(v1.begin(), v1.end(), mem_fun<bool, StoreVals>(&StoreVals::display));
    cout << endl;

    // Use of mem_fun calling member function through a pointer
    // square each value in the vector using squareval ()
    for_each(v1.begin(), v1.end(), mem_fun<int, StoreVals>(&StoreVals::squareval));   
    cout << "The squared values are: " ;
    for_each(v1.begin(), v1.end(), mem_fun<bool, StoreVals>(&StoreVals::display));
    cout << endl;

    // Use of mem_fun1 calling member function through a pointer
    // subtract 5 from each value in the vector using lessconst ()
    for_each(v1.begin(), v1.end(), 
        bind2nd (mem_fun1<int, StoreVals,int>(&StoreVals::lessconst), 5));   
    cout << "The squared values less 5 are: " ;
    for_each(v1.begin(), v1.end(), mem_fun<bool, StoreVals>(&StoreVals::display));
    cout << endl;
}

Output

The original values stored are: 5 10 15 20 25 
The squared values are: 25 100 225 400 625 
The squared values less 5 are: 20 95 220 395 620 

需求

標題: <functional>

命名空間: std

請參閱

參考

標準樣板程式庫