函式模板
<functional>

std::bind

簡單 (1)
template <class Fn, class... Args>  /* unspecified */ bind (Fn&& fn, Args&&... args);
帶返回型別 (2)
template <class Ret, class Fn, class... Args>  /* unspecified */ bind (Fn&& fn, Args&&... args);
繫結函式引數
返回一個基於 fn 的函式物件,但其引數已繫結到 args

每個引數可以繫結到一個,也可以是佔位符
- 如果繫結到,呼叫返回的函式物件時將始終使用該值作為引數。
- 如果是佔位符,呼叫返回的函式物件時會將呼叫時傳遞的引數轉發過去(其順序由佔位符指定)。

呼叫返回的物件返回的型別與 fn 相同,除非作為 Ret (2) 指定了特定的返回型別(請注意,Ret 是唯一一個不能透過傳遞給此函式的引數隱式推導的模板引數)。

返回物件的型別具有以下屬性
  • 其函式呼叫返回的型別與 fn 相同,並將引數繫結到 args...(或對於佔位符進行轉發)。
  • 對於(1),它可能有一個成員 result_type:如果 Fn 是指向函式或成員函式的指標型別,則定義為其返回型別的別名。否則,如果存在這樣的成員型別,則定義為 Fn::result_type
  • 對於(2),它有一個成員 result_type,定義為 Ret 的別名。
  • 它是可移動構造的,如果其所有引數的型別都是可複製構造的,那麼它也是可複製構造的。這兩個建構函式都不會丟擲異常,前提是 FnArgs...decay types 的相應建構函式都不丟擲異常。

引數

fn
一個函式物件、指向函式的指標或指向成員的指標。
Fndecay type 必須是可以從 fn 移動構造的。
args...
要繫結的引數列表:可以是值,也可以是佔位符
Args... 中的型別,其decay types 必須可以從 args... 中的相應引數移動構造
如果任何引數的decay typereference_wrapper,則它會繫結到其引用的值。

返回值

一個函式物件,當呼叫它時,會呼叫 fn 並將其引數繫結到 args

如果 fn 是指向成員的指標,則返回的函式期望的第一個引數是 fn 指向成員的類物件(或其引用、或其指標)。

示例

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
34
35
36
37
38
39
// bind example
#include <iostream>     // std::cout
#include <functional>   // std::bind

// a function: (also works with function object: std::divides<double> my_divide;)
double my_divide (double x, double y) {return x/y;}

struct MyPair {
  double a,b;
  double multiply() {return a*b;}
};

int main () {
  using namespace std::placeholders;    // adds visibility of _1, _2, _3,...

  // binding functions:
  auto fn_five = std::bind (my_divide,10,2);               // returns 10/2
  std::cout << fn_five() << '\n';                          // 5

  auto fn_half = std::bind (my_divide,_1,2);               // returns x/2
  std::cout << fn_half(10) << '\n';                        // 5

  auto fn_invert = std::bind (my_divide,_2,_1);            // returns y/x
  std::cout << fn_invert(10,2) << '\n';                    // 0.2

  auto fn_rounding = std::bind<int> (my_divide,_1,_2);     // returns int(x/y)
  std::cout << fn_rounding(10,3) << '\n';                  // 3

  MyPair ten_two {10,2};

  // binding members:
  auto bound_member_fn = std::bind (&MyPair::multiply,_1); // returns x.multiply()
  std::cout << bound_member_fn(ten_two) << '\n';           // 20

  auto bound_member_data = std::bind (&MyPair::a,ten_two); // returns ten_two.a
  std::cout << bound_member_data() << '\n';                // 10

  return 0;
}

輸出

5
5
0.2
3
20
10


資料競爭

可以透過呼叫來訪問和/或修改引數。

異常安全

基本保證:如果丟擲異常,所有涉及的物件都將保持有效狀態。
此函式僅在構造其任何內部元素(FnArgs...decay types)時可能丟擲異常。

另見