public member function
<functional>

std::reference_wrapper::operator()

template <class... ArgTypes>  typename result_of<type&(ArgTypes&&...)>::type    operator() (ArgTypes&&... args) const;
訪問元素 (函式形式)
訪問被引用的元素。

效果取決於 reference_wrapper 物件引用的型別(即其類模板引數 T,別名為成員 type

  • 如果 type 是一個 *函式* 或一個 *函式物件型別*,則呼叫它並向前傳遞引數給函式。
  • 如果 type 是一個 *指向非靜態成員函式的指標*,則使用第一個引數作為呼叫成員的物件(這可能是一個物件、引用或指向它的指標),並將剩餘的引數轉發給函式。
  • 如果 type 是一個 *指向非靜態資料成員的指標*,它應該用單個引數呼叫,並且該函式返回對其引數成員的引用(該引數可以是一個物件、引用或指向它的指標)。

引數

args...
呼叫的引數。
如果 type 是一個 *成員指標*,第一個引數應為定義該成員的物件(或其引用或指標)。

返回值

如果函式執行函式呼叫,則返回該函式的返回值。
否則,它返回被訪問成員的引用。

type 是描述被引用型別的成員型別(它是類模板引數 T 的別名)。

示例

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
33
// reference_wrapper::operator()
#include <iostream>     // std::cout
#include <functional>   // std::reference_wrapper, std::plus

struct AB {
  int a,b;
  int sum() {return a+b;}
};

 int ten() {return 10;}            // function

int main () {
  std::plus<int> plus_ints;        // function object
  int AB::* p_a = &AB::a;          // pointer to data member
  int(AB::* p_sum)() = &AB::sum;   // pointer to member function

  // construct reference_wrappers using std::ref:
  auto ref_ten = std::ref(ten);             // function
  auto ref_plus_ints = std::ref(plus_ints); // function object
  auto ref_AB_sum = std::ref(p_sum);        // pointer to member function
  auto ref_AB_a = std::ref(p_a);            // pointer to data member

  AB ab {100,200};

  // invocations:
  std::cout << ref_ten() << '\n';
  std::cout << ref_plus_ints(5,10) << '\n';
  std::cout << ref_AB_sum(ab) << '\n';
  std::cout << ref_AB_a( ab) << '\n';
  std::cout << ref_AB_a(&ab) << '\n';       // (also ok with pointer)

  return 0;
}

輸出
10
15
300
100
100


資料競爭

物件及其引用的元素都會被訪問。

異常安全

提供與被訪問元素相同的級別。

另見