std::move_only_function::operator()
來自 cppreference.com
< cpp | utility | functional | move only function
R operator()( Args... args ) /*cv*/ /*ref*/ noexcept(/*noex*/); |
(C++23 起) | |
以引數 args
呼叫儲存的可呼叫目標。operator()
的 /*cv*/、/*ref*/ 和 /*noex*/ 部分與 std::move_only_function
的模板引數相同。
等價於 return std::invoke_r<R>(/*cv-ref-cast*/(f), std::forward<Args>(args)...);,其中 f
是一個表示 *this 目標物件的 cv 無限定左值,而 /*cv-ref-cast*/(f) 等價於
- 若 cv ref 為空或是 &,則為 f,或
- 若 cv ref 是 const 或 const &,則為 std::as_const(f),或
- 若 cv ref 是 &&,則為 std::move(f),或
- 若 cv ref 是 const &&,則為 std::move(std::as_const(f))。
若 *this 為空,則行為未定義。
目錄 |
[編輯] 引數
args | - | - 傳遞給儲存的可呼叫目標的引數 |
[編輯] 返回值
std::invoke_r<R>(/*cv-ref-cast*/(f), std::forward<Args>(args)...).
[編輯] 異常
傳播底層函式呼叫所丟擲的異常。
[編輯] 示例
以下示例展示了 std::move_only_function 如何透過值傳遞給其他函式。此外,它還展示了 std::move_only_function 如何儲存 lambda。
執行此程式碼
#include <iostream> #include <functional> void call(std::move_only_function<int() const> f) // can be passed by value { std::cout << f() << '\n'; } int normal_function() { return 42; } int main() { int n = 1; auto lambda = [&n](){ return n; }; std::move_only_function<int() const> f = lambda; call(std::move(f)); n = 2; call(lambda); f = normal_function; call(std::move(f)); }
輸出
1 2 42
[編輯] 參閱
呼叫目標 ( std::function<R(Args...)> 的公開成員函式) | |
呼叫儲存的函式 ( std::reference_wrapper<T> 的公開成員函式) | |
(C++17)(C++23) |
用給定的引數呼叫任何可呼叫 (Callable) 物件 並可指定返回型別(C++23 起) (函式模板) |