std::move_only_function::operator()
来自cppreference.com
< cpp |
utility | functional | move
only function
工具库
函数对象
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
旧绑定器与适配器 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
std::move_only_function
成员函数 | ||||
(C++23)
|
||||
(C++23)
|
||||
move_only_function::operator()
(C++23)
|
||||
非成员函数 | ||||
(C++23)
|
||||
(C++23)
|
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) 等价于:
- f ,若 cv ref 为空或 & ,或
- std::as_const(f) ,若 cv ref 为 const 或 const & ,或
- std::move(f) ,若 cv ref 为 && ,或
- std::move(std::as_const(f)) ,若 cv ref 为 const && 。
若 *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) // 能按值传递 { 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)
|
以给定实参和可能指定的返回类型 (C++23 起)调用任意可调用 (Callable)
对象 (函数模板) |