std::make_optional
Aus de.cppreference.net
| Definiert in Header <optional>
|
||
template< class T >
constexpr std::optional<std::decay_t<T>> make_optional( T&& value );
|
(1) | (seit C++17) |
template< class T, class... Args >
constexpr std::optional<T> make_optional( Args&&... args );
|
(2) | (seit C++17) |
template< class T, class U, class... Args >
constexpr std::optional<T> make_optional( std::initializer_list<U> il,
Args&&... args );
|
(3) | (seit C++17) |
1) Erzeugt ein optional-Objekt aus
value. Effektiv wird std::optional<std::decay_t<T>>(std::forward<T>(value)) aufgerufen.2) Erzeugt ein optional-Objekt, das direkt aus
Diese Überladung nimmt nur an der Überladungsauflösung teil, wenn
args... konstruiert wird. Entspricht return std::optional<T>(std::in_place, std::forward<Args>(args)...);.Diese Überladung nimmt nur an der Überladungsauflösung teil, wenn
std::is_constructible_v<T, Args...> true ist.
3) Erzeugt ein optional-Objekt, das direkt aus
Diese Überladung nimmt nur an der Überladungsauflösung teil, wenn
il und args... konstruiert wird. Entspricht return std::optional<T>(std::in_place, il, std::forward<Args>(args)...);.Diese Überladung nimmt nur an der Überladungsauflösung teil, wenn
std::is_constructible_v<T, std::initializer_list<U>&, Args...> true ist.
Parameter
| value | - | der Wert, mit dem das optionale Objekt konstruiert werden soll |
| il, args | - |
Argumente, die an den Konstruktor von
T
übergeben werden sollen
|
Rückgabewert
Das konstruierte optionale Objekt.
Ausnahmen
Wirft jede Ausnahme, die vom Konstruktor von
T
geworfen wird.
Hinweise
T
muss für die Überladungen
(
2,3
)
nicht verschiebbar sein, garantiert durch Copy Elision.
Beispiel
Diesen Code ausführen
#include <iomanip> #include <iostream> #include <optional> #include <string> #include <vector> int main() { auto op1 = std::make_optional<std::vector<char>>({'a','b','c'}); std::cout << "op1: "; for (char c : op1.value()) std::cout << c << ','; auto op2 = std::make_optional<std::vector<int>>(5, 2); std::cout << "\nop2: "; for (int i : *op2) std::cout << i << ','; std::string str{"hello world"}; auto op3 = std::make_optional<std::string>(std::move(str)); std::cout << "\nop3: " << std::quoted(op3.value_or("empty value")) << '\n'; std::cout << "str: " << std::quoted(str) << '\n'; }
Mögliche Ausgabe:
op1: a,b,c, op2: 2,2,2,2,2, op3: "hello world" str: ""
Siehe auch
konstruiert das
optional
Objekt
(öffentliche Elementfunktion) |