C++ 命名要求: FunctionObject
一个 FunctionObject 类型是指可以放在函数调用运算符左侧使用的对象的类型。
要求
如果满足以下条件,类型 T 满足 FunctionObject:
- 类型 T 满足 std::is_object,并且
给定
f
,类型为T
或const T
的值args
,合适的参数列表,可以为空
以下表达式必须有效
公共 | 表达式 | 要求 |
公共 | f(args) | 执行函数调用 |
备注
函数和函数引用不是函数对象类型,但由于函数到指针的隐式转换,它们可以在预期函数对象类型的地方使用。
标准库
- 所有函数指针都满足此要求。
- 所有在 <functional> 中定义的函数对象
- <functional> 中某些函数的返回类型
示例
演示不同类型的函数对象
#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)