命名空间
变体
操作

std::monostate

来自 cppreference.cn
< cpp‎ | utility‎ | variant
 
 
 
 
定义于头文件 <variant>
定义于头文件 <utility>
(since C++26)
struct monostate { };
(since C++17)

单元类型,旨在用作 std::variant 中行为良好的空替代项。 特别是,不可默认构造类型的变体可以将 std::monostate 列为其第一个替代项:这使得变体本身可默认构造。

目录

[edit] 成员函数

(构造函数)
(隐式声明)
平凡隐式默认/复制/移动构造函数
(公共成员函数)
(析构函数)
(隐式声明)
平凡隐式析构函数
(公共成员函数)
operator=
(隐式声明)
平凡隐式复制/移动赋值
(公共成员函数)

[edit] 非成员函数

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

constexpr bool operator==( monostate, monostate ) noexcept { return true; }
(1) (since C++17)
(2)
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)

std::monostate 的所有实例都比较相等。

<<=>>=!= 运算符分别从 operator<=>operator== 合成

(since C++20)

[edit] 辅助类

std::hash<std::monostate>

template <>
struct std::hash<monostate>;
(since C++17)

std::monostate 特化 std::hash 算法。

[edit] 示例

#include <cassert>
#include <iostream>
#include <variant>
 
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 = 42;
    std::cout << "std::get: " << std::get<S>(var).i << '\n'
              << "std::hash: " << std::hex << std::showbase
              << std::hash<std::monostate>{}(std::monostate{}) << '\n';
}

可能的输出

std::get: wrong index for variant
std::get: 42
std::hash: 0xffffffffffffe19f

[edit] 参见

构造 variant 对象
(公共成员函数) [编辑]