C++ named requirements: FunctionObject
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Ein FunctionObject -Typ ist der Typ eines Objekts, das auf der linken Seite des Funktionsaufrufoperators verwendet werden kann.
Inhaltsverzeichnis |
Anforderungen
Der Typ
T
erfüllt die Anforderungen von
FunctionObject
wenn
-
Der Typ
Terfüllt std::is_object , und
Gegeben
-
f, ein Wert vom TypToderconst T, -
args, geeignete Argumentenliste, die leer sein kann.
Die folgenden Ausdrücke müssen gültig sein:
| Expression | Anforderungen |
|---|---|
| f ( args ) | führt einen Funktionsaufruf aus |
Hinweise
Funktionen und Referenzen auf Funktionen sind keine Funktionsobjekttypen, können jedoch aufgrund der impliziten Konvertierung von Funktion zu Zeiger in Kontexten verwendet werden, wo Funktionsobjekttypen erwartet werden.
Standardbibliothek
- Alle Zeiger auf Funktionen erfüllen diese Anforderung.
- Alle Funktionsobjekte, die in <functional> definiert sind.
- Einige Rückgabetypen von Funktionen aus <functional> .
Beispiel
Demonstriert verschiedene Arten von Funktionsobjekten.
#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) }
Ausgabe:
foo(1) foo(2) foo(3) foo(3) S::operator(4) S::operator(4) lambda(5) lambda(5) bar(6) bar(6) bar(6)
Siehe auch
|
ein Typ, für den der Aufrufvorgang definiert ist
(Named Requirement) |