function template
<functional>

std::mem_fun

template <class S, class T> mem_fun_t<S,T> mem_fun (S (T::*f)());template <class S, class T, class A> mem_fun1_t<S,T,A> mem_fun (S (T::*f)(A));template <class S, class T> const_mem_fun_t<S,T> mem_fun (S (T::*f)() const);template <class S, class T, class A> const_mem_fun1_t<S,T,A> mem_fun (S (T::*f)(A) const);
將成員函式轉換為函式物件(指標版本)
返回一個封裝型別為T的成員函式f的函式物件。該成員函式返回型別為S的值,並且可以選擇性地接受一個型別為A的引數。

此函式返回的函式物件期望一個指向物件的指標作為其(第一個)引數,用於operator()。一個類似的函式mem_fun_ref生成相同的函式,但期望一個物件的引用作為(第一個)引數。

函式物件是定義了成員函式operator()的類物件。該成員函式允許物件以與常規函式呼叫相同的語法來使用。幾個標準的演算法介面卡被設計用來與函式物件一起使用。

它的定義與以下行為相同:

1
2
3
4
5
6
7
8
9
10
11
template <class S, class T> mem_fun_t<S,T> mem_fun (S (T::*f)())
{ return mem_fun_t<S,T>(f); }

template <class S, class T, class A> mem_fun1_t<S,T,A> mem_fun (S (T::*f)(A))
{ return mem_fun1_t<S,T,A>(f); }

template <class S, class T> const_mem_fun_t<S,T> mem_fun (S (T::*f)() const)
{ return const_mem_fun_t<S,T>(f); }

template <class S, class T, class A> const_mem_fun1_t<S,T,A> mem_fun (S (T::*f)(A) const)
{ return const_mem_fun1_t<S,T,A>(f); }

模板引數

S
成員函式的返回型別。
T
成員函式所屬的型別(類)。
A
成員函式接受的引數的型別(如果有)。

引數

f
指向成員函式的指標,該函式接受一個引數(型別為A)或不接受任何引數,並返回一個型別為S的值。

返回值

一個函式物件,它呼叫作為(第一個)引數傳遞的指標所指向物件的成員函式f
如果成員函式接受一個引數,則在函式物件中將其指定為第二個引數。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// mem_fun example
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int main () {
  vector <string*> numbers;

  // populate vector of pointers:
  numbers.push_back ( new string ("one") );
  numbers.push_back ( new string ("two") );
  numbers.push_back ( new string ("three") );
  numbers.push_back ( new string ("four") );
  numbers.push_back ( new string ("five") );

  vector <int> lengths ( numbers.size() );

  transform (numbers.begin(), numbers.end(), lengths.begin(), mem_fun(&string::length));
	
  for (int i=0; i<5; i++) {
    cout << *numbers[i] << " has " << lengths[i] << " letters.\n";
  }

  // deallocate strings:
  for (vector<string*>::iterator it = numbers.begin(); it!=numbers.end(); ++it)
    delete *it;

  return 0;
}

輸出

one has 3 letters.
two has 3 letters.
three has 5 letters.
four has 4 letters.
five has 4 letters.


另見