function template
<functional>

std::mem_fun_ref

template <class S, class T>  mem_fun_ref_t<S,T> mem_fun_ref (S (T::*f)());template <class S, class T, class A>  mem_fun1_ref_t<S,T,A> mem_fun_ref (S (T::*f)(A));template <class S, class T>  const_mem_fun_ref_t<S,T> mem_fun_ref (S (T::*f)() const);template <class S, class T, class A>  const_mem_fun1_ref_t<S,T,A> mem_fun_ref (S (T::*f)(A) const);
將成員函式轉換為函式物件(引用版本)
返回一個封裝型別為 T 的成員函式 f 的函式物件。該成員函式返回型別為 S 的值,並且可以選擇性地接受一個型別為 A 的引數。

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template <class S, class T>
  mem_fun_ref_t<S,T> mem_fun_ref (S (T::*f)())
  { return mem_fun_ref_t<S,T>(f); }

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

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

template <class S, class T, class A>
  const_mem_fun1_ref_t<S,T,A> mem_fun_ref (S (T::*f)(A) const)
  { return const_mem_fun1_ref_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
// mem_fun_ref example
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int main () {
  vector<string> numbers;

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

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

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

輸出

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


另見