public member function
<functional>

std::function::target

template <class TargetType>       TargetType* target() noexcept;template <class TargetType> const TargetType* target() const noexcept;
獲取目標物件的指標
返回儲存在 function 物件中的*可呼叫物件*的指標。

由於 function 是一個多型包裝類,它不知道其目標*可呼叫物件*的靜態型別,因此必須顯式指定模板引數 TargetType

TargetType 應與目標型別匹配,以便 typeid(TargetType)==target_type()。否則,該函式總是返回*空指標*。

引數



返回值

如果 typeid(TargetType) 與成員 target_type 返回的值相等,則返回*目標可呼叫物件*的指標。
否則,返回*空指標*。

示例

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
// function::target example
#include <iostream>     // std::cout, std::boolalpha
#include <functional>   // std::function, std::plus, std::minus

int my_plus (int a, int b) {return a+b;}
int my_minus (int a, int b) {return a-b;}

int main () {
  std::function<int(int,int)> foo = my_plus;
  std::function<int(int,int)> bar = std::plus<int>();

  // calling using functional form:
  std::cout << foo(100,20) << '\n';
  std::cout << bar(100,20) << '\n';

  // calling by invoking target:
  std::cout << (*foo.target<int(*)(int,int)>())(100,20) << '\n';
  std::cout << (*bar.target<std::plus<int>>())(100,20) << '\n';

  // changing target directly:
  *foo.target<int(*)(int,int)>() = &my_minus;
  std::cout << foo(100,20) << '\n';

  return 0;
}

輸出
120
120
120
120
80


資料競爭

同時訪問物件及其目標。
返回的指標可用於訪問或修改目標*可呼叫物件*。

異常安全

無異常保證:此成員函式從不丟擲異常。

另見