std::monostate

From cppreference.com
< cpp‎ | utility‎ | variant
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)
 
 
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-constructible.

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

std::operator==, !=, <, <=, >, >=, <=>(std::monostate)

constexpr bool operator==(monostate, monostate) noexcept { return true; }
(since C++17)
constexpr bool operator!=(monostate, monostate) noexcept { return false; }

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; }
(since C++17)
(until C++20)
constexpr std::strong_ordering operator<=>(monostate, monostate) noexcept
{ return std::strong_ordering::equal; }
(since C++20)

All instances of std::monostate compare equal.

The <, <=, >, >=, and != operators are synthesized from operator<=> and operator== respectively.

(since C++20)

Helper classes

std::hash<std::monostate>

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

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

Example

#include <variant>
#include <iostream>
#include <cassert>
 
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; 
    assert(var.index() == 0);
 
    try {
        std::get<S>(var); // throws! We need to assign a value
    }
    catch(const std::bad_variant_access& e) {
        std::cout << e.what() << '\n';
    }
 
    var = 12; 
 
    std::cout << std::get<S>(var).i << '\n';
}

Possible output:

std::get: wrong index for variant
12

See also

constructs the variant object
(public member function)