std::monostate
來自 cppreference.com
定義於標頭檔案 <variant> |
||
在標頭檔案 <utility> 中定義 |
(C++26 起) |
|
struct monostate { }; |
(C++17 起) | |
單元型別,用作 std::variant 中行為良好的空替代。特別是,一個包含不可預設構造型別的 variant 可以將 std::monostate
列為其第一個替代:這使得 variant 本身可預設構造。
目錄 |
[編輯] 成員函式
(建構函式) (隱式宣告) |
平凡的隱式預設/複製/移動建構函式 (公開成員函式) |
(解構函式) (隱式宣告) |
平凡的隱式解構函式 (公開成員函式) |
operator= (隱式宣告) |
平凡的隱式複製/移動賦值 (公開成員函式) |
[編輯] 非成員函式
std::operator==, !=, <, <=, >, >=, <=>(std::monostate)
constexpr bool operator==( monostate, monostate ) noexcept { return true; } |
(1) | (C++17 起) |
(2) | ||
constexpr bool operator!=( monostate, monostate ) noexcept { return false; } constexpr bool operator< ( monostate, monostate ) noexcept { return false; } |
(C++17 起) (C++20 前) |
|
constexpr std::strong_ordering operator<=>( monostate, monostate ) noexcept { |
(C++20 起) | |
所有 std::monostate
例項都比較相等。
|
(C++20 起) |
[編輯] 輔助類
std::hash<std::monostate>
template <> struct std::hash<monostate>; |
(C++17 起) | |
特化 std::monostate
的 std::hash 演算法。
[編輯] 示例
執行此程式碼
#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
[編輯] 參閱
構造 variant 物件(public member function) |