Namespaces
Variants

C++ named requirements: FunctionObject

From cppreference.net
C++ named requirements

一个 FunctionObject 类型是指可在函数调用运算符左侧使用的对象的类型。

目录

要求

类型 T 满足 FunctionObject

给定

  • f ,类型为 T const T 的值,
  • args ,合适的参数列表,可以为空。

以下表达式必须有效:

表达式 要求
f ( args ) 执行函数调用

注释

函数及函数引用本身并非函数对象类型,但由于存在 函数到指针的隐式转换 ,它们可以在需要函数对象类型的场景中使用。

标准库

示例

演示不同类型的函数对象。

#include <functional>
#include <iostream>
void foo(int x) { std::cout << "foo(" << x << ")\n"; }
void bar(int x) { std::cout << "bar(" << x << ")\n"; }
int main()
{
    void(*fp)(int) = foo;
    fp(1); // 通过函数指针调用 foo
    std::invoke(fp, 2); // 所有 FunctionObject 类型都是可调用对象
    auto fn = std::function(foo); // 另请参阅 <functional> 中的其他内容
    fn(3);
    fn.operator()(3); // 与 fn(3) 效果相同
    struct S
    {
        void operator()(int x) const { std::cout << "S::operator(" << x << ")\n"; }
    } s;
    s(4); // 调用 s.operator()
    s.operator()(4); // 与 s(4) 相同
    auto lam = [](int x) { std::cout << "lambda(" << x << ")\n"; };
    lam(5); // 调用 lambda
    lam.operator()(5); // 与 lam(5) 相同
    struct T
    {
        using FP = void (*)(int);
        operator FP() const { return bar; }
    } t;
    t(6); // t 被转换为函数指针
    static_cast<void (*)(int)>(t)(6); // 与 t(6) 相同
    t.operator T::FP()(6); // 与 t(6) 相同
}

输出:

foo(1)
foo(2)
foo(3)
foo(3)
S::operator(4)
S::operator(4)
lambda(5)
lambda(5)
bar(6)
bar(6)
bar(6)

参见

定义了调用操作的类型
(具名要求)