std::function<R(Args...)>::operator()
来自cppreference.com
< cpp | utility | functional | function
R operator()( Args... args ) const; |
(C++11 起) | |
以参数 args 调用存储的可调用函数目标。
等效于进行 INVOKE<R>(f, std::forward<Args>(args)...),其中 f 是 *this
的目标对象。
目录 |
[编辑] 参数
args | - | 传递给存储的可调用函数目标的参数 |
[编辑] 返回值
在 R
是 void 时没有返回值。否则返回存储的可调用对象的调用返回值。
[编辑] 异常
在没有存储可调用函数目标,即 !*this == true 时抛出 std::bad_function_call。
[编辑] 示例
下列示例展示能如何将 std::function 按值传递给另一函数。而且,它演示 std::function 能如何存储 lambda。
运行此代码
#include <functional> #include <iostream> void call(std::function<int()> f) // 能按值传递 { 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) |
以给定实参和可能指定的返回类型(C++23 起)调用任意可调用 (Callable) 对象 (函数模板) |