Namespaces
Variants

std::function<R(Args...)>::operator()

来自 zh.cppreference.net
 
 
 
函数对象
函数调用
(C++17)(C++23)
恒等函数对象
(C++20)
透明运算符包装器
(C++14)
(C++14)
(C++14)
(C++14)  
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)

旧式绑定器和适配器
(直到 C++17*)
(直到 C++17*)
(直到 C++17*)
(直到 C++17*)  
(直到 C++17*)
(直到 C++17*)(直到 C++17*)(直到 C++17*)(直到 C++17*)
(直到 C++20*)
(直到 C++20*)
(直到 C++17*)(直到 C++17*)
(直到 C++17*)(直到 C++17*)

(直到 C++17*)
(直到 C++17*)(直到 C++17*)(直到 C++17*)(直到 C++17*)
(直到 C++20*)
(直到 C++20*)
 
 
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> 的公开成员函数)
调用空 std::function 时抛出的异常
(类)
(C++17) (C++23)
以给定参数调用任意 Callable 对象 并可指定返回类型 (C++23 起)
(函数模板)