Namespaces
Variants

std:: variant_npos

From cppreference.net
Utilities library
Definiert im Header <variant>
inline constexpr std:: size_t variant_npos = - 1 ;
(seit C++17)

Dies ist ein spezieller Wert, der dem größten darstellbaren Wert des Typs std:: size_t entspricht und als Rückgabewert von index() verwendet wird, wenn valueless_by_exception() den Wert true hat.

#include <iostream>
#include <stdexcept>
#include <string>
#include <variant>
struct Demon
{
    Demon(int) {}
    Demon(const Demon&) { throw std::domain_error("copy ctor"); }
    Demon& operator= (const Demon&) = default;
};
int main()
{
    std::variant<int, Demon> var{42};
    std::cout
        << std::boolalpha
        << "index == npos: " << (var.index() == std::variant_npos) << '\n';
    try { var = Demon{666}; } catch (const std::domain_error& ex)
    {
        std::cout
            << "Exception: " << ex.what() << '\n'
            << "index == npos: " << (var.index() == std::variant_npos) << '\n'
            << "valueless: " << var.valueless_by_exception() << '\n';
    }
}

Mögliche Ausgabe:

index == npos: false
Exception: copy ctor
index == npos: true
valueless: true

Siehe auch

gibt den nullbasierten Index der Alternative zurück, die vom variant gehalten wird
(öffentliche Elementfunktion)
prüft, ob sich der variant im ungültigen Zustand befindet
(öffentliche Elementfunktion)