C++ 庫 - <functional>



簡介

函式物件是專門設計用於以類似於函式的語法使用的物件。std::function 的例項可以儲存、複製和呼叫任何可呼叫目標——函式、lambda 表示式、bind 表示式或其他函式物件,以及指向成員函式的指標和指向資料成員的指標。

宣告

以下是 std::function 的宣告。

template<class >
class function; 

C++11

template< class R, class... Args >
class function<R(Args...)>

引數

  • R - 返回值型別。

  • argument_type - 如果 sizeof...(Args)==1 且 T 是 Args 中第一個也是唯一的型別,則為 T。

示例

在下面的 std::function 示例中。

#include <functional>
#include <iostream>

struct Foo {
   Foo(int num) : num_(num) {}
   void print_add(int i) const { std::cout << num_+i << '\n'; }
   int num_;
};
 
void print_num(int i) {
   std::cout << i << '\n';
}

struct PrintNum {
   void operator()(int i) const {
      std::cout << i << '\n';
   }
};

int main() {
   std::function<void(int)> f_display = print_num;
   f_display(-9);

   std::function<void()> f_display_42 = []() { print_num(42); };
   f_display_42();

   std::function<void()> f_display_31337 = std::bind(print_num, 31337);
   f_display_31337();

   std::function<void(const Foo&, int)> f_add_display = &Foo::print_add;
   const Foo foo(314159);
   f_add_display(foo, 1);

   std::function<int(Foo const&)> f_num = &Foo::num_;
   std::cout << "num_: " << f_num(foo) << '\n';

   using std::placeholders::_1;
   std::function<void(int)> f_add_display2= std::bind( &Foo::print_add, foo, _1 );
   f_add_display2(2);
 
   std::function<void(int)> f_add_display3= std::bind( &Foo::print_add, &foo, _1 );
   f_add_display3(3);

   std::function<void(int)> f_display_obj = PrintNum();
   f_display_obj(18);
}

示例輸出應如下所示:

-9
42
31337
314160
num_: 314159
314161
314162
18

成員函式

序號 成員函式 定義
1 (建構函式) 用於構造新的 std::function 例項
2 (解構函式) 用於銷燬 std::function 例項
3 operator= 用於分配新的目標
4 swap 用於交換內容
5 assign 用於分配新的目標
6 operator bool 用於檢查是否包含有效目標
7 operator() 用於呼叫目標

非成員函式

序號 非成員函式 定義
1 std::swap 專門化 std::swap 演算法
2 operator== operator!= 將 std::function 與 nullptr 進行比較

運算子類

序號 運算子類 定義
1 bit_and 位與函式物件類
2 bit_or 位或函式物件類
3 bit_xor 位異或函式物件類
3 divides 除法函式物件類
4 equal_to 用於相等比較的函式物件類
5 greater 用於大於不等式比較的函式物件類
6 greater_equal 用於大於或等於比較的函式物件類
7 less 用於小於不等式比較的函式物件類
8 less_equal 用於小於或等於比較的函式物件類
9 logical_and 邏輯與函式物件類
10 logical_not 邏輯非函式物件類
11 logical_or 邏輯或函式物件類
12 minus 減法函式物件類
13 modulus 取模函式物件類
14 multiplies 乘法函式物件類
15 negate 負函式物件類
16 not_equal_to 用於不相等比較的函式物件類
17 plus 加法函式物件類
廣告

© . All rights reserved.