W3cubDocs

/C++

std::monostate

Defined in header <variant>
struct monostate { }
(since C++17)

Unit type intended for use as a well-behaved empty alternative in std::variant. In particular, a variant of non-default-constructible types may list std::monostate as its first alternative: this makes the variant itself default-contructible.

Member functions

(constructor)
(implicitly declared)
trivial implicit default/copy/move constructor
(public member function)
(destructor)
(implicitly declared)
trivial implicit destructor
(public member function)
operator=
(implicitly declared)
trivial implicit copy/move assignment
(public member function)

Non-member functions

constexpr bool operator<(monostate, monostate) noexcept { return false; }
constexpr bool operator>(monostate, monostate) noexcept { return false; }
constexpr bool operator<=(monostate, monostate) noexcept { return true; }
constexpr bool operator>=(monostate, monostate) noexcept { return true; }
constexpr bool operator==(monostate, monostate) noexcept { return true; }
constexpr bool operator!=(monostate, monostate) noexcept { return false; }

All instances of std::monostate compare equal.

Exceptions

noexcept specification:
noexcept

Helper classes

std::hash<std::monostate>

template <> struct std::hash<monostate>;

Specializes the std::hash algorithm for std::monostate.

Example

#include <variant>
#include <iostream>
 
struct S
{
    S(int i) : i(i) {}
    int i;
};
 
int main() {
 
    // Without the monostate type this declaration will fail.
    // This is because S is not default-constructible.
 
    std::variant<std::monostate, S> var; 
 
    // var.index() is now 0 - the first element
    // std::get<S> will throw! We need to assign a value
 
    var = 12; 
 
    std::cout << std::get<S>(var).i << '\n';
}

Output:

12

See also

constructs the variant object
(public member function)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/utility/variant/monostate