C++ 具名要求:函数对象 (FunctionObject)
来自cppreference.com
函数对象 (FunctionObject) 类型是可用在函数调用运算符左侧的对象的类型。
要求
若满足下列条件,则类型 T 满足函数对象 (FunctionObject)
- 类型
T满足 std::is_object,且
给定
T或const T类型的值fargs,为适合的实参列表,可以为空
则下列表达式必须合法:
| 表达式 | 要求 |
|---|---|
f(args)
|
进行函数调用 |
注解
函数和到函数的引用不是函数对象类型,但因为函数到指针隐式转换,它们能用在期待函数对象类型的地方。
标准库
- 所有函数指针都满足此要求。
- 所有定义于 <functional> 的函数对象。
- 某些 <functional> 的函数的返回类型。
示例
展示不同类型的函数对象。
运行此代码
#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 类型都 Callable
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)
参阅
| 定义了调用操作的类型 (具名要求) |