Namespaces
Variants

std::optional<T>:: or_else

From cppreference.net
Utilities library
template < class F >
constexpr optional or_else ( F && f ) const & ;
(1) (seit C++23)
template < class F >
constexpr optional or_else ( F && f ) && ;
(2) (seit C++23)

Gibt * this zurück, falls es einen Wert enthält. Andernfalls wird das Ergebnis von f zurückgegeben.

Das Programm ist fehlerhaft, wenn std:: remove_cvref_t < std:: invoke_result_t < F >> nicht identisch mit std:: optional < T > ist.

1) Entspricht return * this ? * this : std:: forward < F > ( f ) ( ) ; . Diese Überladung nimmt nur dann an der Überladungsauflösung teil, wenn sowohl std:: copy_constructible < T > als auch std:: invocable < F > modelliert werden.
2) Entspricht return * this ? std :: move ( * this ) : std:: forward < F > ( f ) ( ) ; . Diese Überladung nimmt nur dann an der Überladungsauflösung teil, wenn sowohl std:: move_constructible < T > als auch std:: invocable < F > modelliert werden.

Inhaltsverzeichnis

Parameter

f - eine Funktion oder ein Callable Objekt, das einen std:: optional < T > zurückgibt

Rückgabewert

* this oder das Ergebnis von f , wie oben beschrieben.

Hinweise

Feature-Test Makro Wert Std Feature
__cpp_lib_optional 202110L (C++23) Monadische Operationen in std::optional

Beispiel

#include <iostream>
#include <optional>
#include <string>
int main()
{
    using maybe_int = std::optional<int>;
    auto valueless = []
    {
        std::cout << "Valueless: ";
        return maybe_int{0};
    };
    maybe_int x;
    std::cout << x.or_else(valueless).value() << '\n';
    x = 42;
    std::cout << "Has value: ";
    std::cout << x.or_else(valueless).value() << '\n';
    x.reset();
    std::cout << x.or_else(valueless).value() << '\n';
}

Ausgabe:

Valueless: 0
Has value: 42
Valueless: 0

Siehe auch

gibt den enthaltenen Wert zurück, falls verfügbar, andernfalls einen anderen Wert
(öffentliche Elementfunktion)
(C++23)
gibt das Ergebnis der gegebenen Funktion auf den enthaltenen Wert zurück, falls vorhanden, oder ein leeres optional andernfalls
(öffentliche Elementfunktion)
(C++23)
gibt ein optional zurück, das den transformierten enthaltenen Wert enthält, falls vorhanden, oder ein leeres optional andernfalls
(öffentliche Elementfunktion)