命名空间
变体
操作

std::move_only_function::operator()

来自 cppreference.cn
 
 
 
函数对象
函数调用
(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 ) /*cv*/ /*ref*/ noexcept(/*noex*/);
(自 C++23 起)

使用参数 args 调用存储的可调用目标。 /*cv*//*ref*//*noex*/ 部分的 operator()std::move_only_function 的模板参数的那些部分相同。

等效于 return std::invoke_r<R>(/*cv-ref-cast*/(f), std::forward<Args>(args)...);,其中 f 是一个 cv 无限定左值,表示 *this 的目标对象,并且 /*cv-ref-cast*/(f) 等价于

  • f 如果 cv ref 是空或者 &,或者
  • std::as_const(f) 如果 cv refconst 或者 const &,或者
  • std::move(f) 如果 cv ref&&,或者
  • std::move(std::as_const(f)) 如果 cv refconst &&

如果 *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)
使用给定参数调用任何 可调用 对象 并可能指定返回类型(自 C++23 起)
(函数模板) [编辑]