命名空间
变体
操作

C++ 命名要求: FunctionObject

来自 cppreference.cn
 
 
C++ 命名要求
 

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

目录

[编辑] 要求

类型 T 满足 FunctionObject,如果

给定

  • f,类型 Tconst 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); // calls foo using the pointer to function
 
    std::invoke(fp, 2); // all FunctionObject types are Callable
 
    auto fn = std::function(foo); // see also the rest of <functional>
    fn(3);
    fn.operator()(3); // the same effect as fn(3)
 
    struct S
    {
        void operator()(int x) const { std::cout << "S::operator(" << x << ")\n"; }
    } s;
    s(4); // calls s.operator()
    s.operator()(4); // the same as s(4)
 
    auto lam = [](int x) { std::cout << "lambda(" << x << ")\n"; };
    lam(5); // calls the lambda
    lam.operator()(5); // the same as lam(5)
 
    struct T
    {
        using FP = void (*)(int);
        operator FP() const { return bar; }
    } t;
    t(6); // t is converted to a function pointer
    static_cast<void (*)(int)>(t)(6); // the same as t(6)
    t.operator T::FP()(6); // the same as 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)

[编辑] 参见

为其定义了调用操作的类型
(命名要求)