std::function<R(Args...)>::operator()
來自 cppreference.com
R operator()( Args... args ) const; |
(C++11 起) | |
使用引數 args 呼叫儲存的可呼叫函式目標。
實質上執行 INVOKE<R>(f, std::forward<Args>(args)...),其中 f 是 *this 的目標物件。
目錄 |
[編輯] 引數
args | - | 傳遞給儲存的可呼叫函式目標的引數 |
[編輯] 返回值
如果 R
是 void,則無。否則是儲存的可呼叫物件呼叫的返回值。
[編輯] 異常
如果 *this 沒有儲存可呼叫函式目標(即 !*this == true),則丟擲 std::bad_function_call。
[編輯] 示例
以下示例展示瞭如何按值將 std::function 傳遞給其他函式。此外,它還展示了 std::function 如何儲存 lambda 表示式。
執行此程式碼
#include <functional> #include <iostream> void call(std::function<int()> f) // can be passed by value { std::cout << f() << '\n'; } int normal_function() { return 42; } int main() { int n = 1; std::function<int()> f; try { call(f); } catch (const std::bad_function_call& ex) { std::cout << ex.what() << '\n'; } f = [&n](){ return n; }; call(f); n = 2; call(f); f = normal_function; call(f); std::function<void(std::string, int)> g; g = [](std::string str, int i) { std::cout << str << ' ' << i << '\n'; }; g("Hi", 052); }
可能的輸出
bad_function_call 1 2 42 Hi 42
[編輯] 參閱
呼叫目標 ( std::move_only_function 的公共成員函式) | |
呼叫儲存的函式 ( std::reference_wrapper<T> 的公共成員函式) | |
(C++11) |
呼叫空的 std::function 時丟擲的異常 (類) |
(C++17起)(C++23起) |
使用給定引數呼叫任何 可呼叫 (Callable) 物件 並可能指定返回型別(C++23 起) (函式模板) |