跳到主要内容

C++ 命名要求: FunctionObject

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

要求

如果满足以下条件,类型 T 满足 FunctionObject

给定

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

以下表达式必须有效

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

备注

函数和函数引用不是函数对象类型,但由于函数到指针的隐式转换,它们可以在预期函数对象类型的地方使用。

标准库

示例

演示不同类型的函数对象

#include <iostream>

void foo(int x) { std::cout << "foo(" << x << ")\n"; }

int main()
{
void(*fp)(int) = foo;
fp(1); // calls foo using the pointer to function

struct S {
void operator()(int x) const { std::cout << "S::operator(" << x << ")\n"; }
} s;
s(2); // calls s.operator()
s.operator()(3); // the same

auto lam = [](int x) { std::cout << "lambda(" << x << ")\n"; };
lam(4); // calls the lambda
lam.operator()(5); // the same

struct T {
static void bar(int x) { std::cout << "T::bar(" << x << ")\n"; }
using FP = void (*)(int);
operator FP() const { return bar; }
} t;
t(6); // t is converted to a function pointer
static_cast<void (*)(int)>(t)(7); // the same
}
结果
foo(1)
S::operator(2)
S::operator(3)
lambda(4)
lambda(5)
T::bar(6)
T::bar(7)

C++ 命名要求: FunctionObject

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

要求

如果满足以下条件,类型 T 满足 FunctionObject

给定

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

以下表达式必须有效

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

备注

函数和函数引用不是函数对象类型,但由于函数到指针的隐式转换,它们可以在预期函数对象类型的地方使用。

标准库

示例

演示不同类型的函数对象

#include <iostream>

void foo(int x) { std::cout << "foo(" << x << ")\n"; }

int main()
{
void(*fp)(int) = foo;
fp(1); // calls foo using the pointer to function

struct S {
void operator()(int x) const { std::cout << "S::operator(" << x << ")\n"; }
} s;
s(2); // calls s.operator()
s.operator()(3); // the same

auto lam = [](int x) { std::cout << "lambda(" << x << ")\n"; };
lam(4); // calls the lambda
lam.operator()(5); // the same

struct T {
static void bar(int x) { std::cout << "T::bar(" << x << ")\n"; }
using FP = void (*)(int);
operator FP() const { return bar; }
} t;
t(6); // t is converted to a function pointer
static_cast<void (*)(int)>(t)(7); // the same
}
结果
foo(1)
S::operator(2)
S::operator(3)
lambda(4)
lambda(5)
T::bar(6)
T::bar(7)