C++ 命名要求: FunctionObject
來自 cppreference.com
FunctionObject 型別是可以在函式呼叫運算子左側使用的物件的型別。
目錄 |
[編輯] 要求
型別 T
滿足 FunctionObject,如果
- 型別
T
滿足 std::is_object,並且
給定
-
f
,型別為T
或const T
的值, -
args
,合適的引數列表,可以為空。
以下表達式必須有效
表示式 | 要求 |
---|---|
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); // 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)
[編輯] 另請參閱
定義了 invoke 操作的型別 (命名要求) |