C++ 函式庫 - operator()



描述

它使用引數 args 呼叫儲存的可呼叫函式目標。

宣告

以下是 std::function::function::operator() 的宣告

R operator()( Args... args ) const;

C++11

R operator()( Args... args ) const;

引數

args − 傳遞給儲存的可呼叫函式目標的引數。

返回值

如果 R 為 void,則返回 none。否則返回呼叫儲存的可呼叫物件的返回值。

異常

noexcept: 它不會丟擲任何異常。

示例

以下為 std::function::operator() 的示例。

#include <iostream>
#include <functional>
 
void call(std::function<int()> f) {
   std::cout << f() << '\n';
}

int normal_function() {
   return 50;
}

int main() {
   int n = 4;
   std::function<int()> f = [&n](){ return n; };
   call(f);

   n = 5;
   call(f);

   f = normal_function;
   call(f);
}

輸出應如下所示:

4
5
50
functional.htm
廣告