std::function<R(Args...)>:: operator()
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Old binders and adaptors | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
|
(until C++17)
|
||||
|
function::operator()
|
||||
| Non-member functions | ||||
|
(until C++20)
|
||||
| Helper classes | ||||
|
(until C++17)
|
||||
| Deduction guides (C++17) |
|
R operator
(
)
(
Args...
args
)
const
;
|
(自 C++11 起) | |
以参数 args 调用存储的可调用函数目标。
实际上执行的是 INVOKE<R> ( f, std:: forward < Args > ( args ) ... ) ,其中 f 是 * this 的 目标对象 。
目录 |
参数
| args | - | 传递给存储的可调用函数目标的参数 |
返回值
若
R
为
void
则返回空。否则返回所存储可调用对象被调用时的返回值。
异常
当 * this 未存储可调用函数目标时抛出 std::bad_function_call ,即 ! * this == true 。
示例
以下示例展示了如何通过值传递 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 起)
(函数模板) |