yohhoyの日記

技術的メモをしていきたい日記

std::monostateのハッシュ値

C++標準ライブラリの直和データ型std::variant<...>と組み合わせて空の状態を表すstd::monostateオブジェクトでは、std::hashによるハッシュ計算がサポートされる。*1

各C++処理系で算出されるハッシュ値の一覧(括弧内は併記コメント/定数名):

  • GCC: -7777(__magic_monostate_hash)*2
  • Clang: 66740831(return a fundamentally attractive random value.)*3
  • MSVC: 1729(Arbitrary value)*4

2026-03-26追記:

  • Clang(LLVM/libc++)のマジックナンバー66740831は、2016年12月のコミット*5で導入された。2014年CODATA推奨値による万有引力定数G = 6.6470831由来と考えられる。
  • MSVCのマジックナンバー1729は、「ハーディ・ラマヌジャン数」=2つの正の立方数の和2通りで表せる最小の数として知られている。1729 = 1^3 + 12^3 = 9^3 + 10^3。

C++20 20.7.8, 20.7.12より引用。

struct monostate{};

The class monostate can serve as a first alternative type for a variant to make the variant type default constructible.

template<class... Types> struct hash<variant<Types...>>;

The specialization hash<variant<Types...>> is enabled (20.14.18) if and only if every specialization in hash<remove_const_t<Types>>... is enabled. The member functions are not guaranteed to be noexcept.

template<> struct hash<monostate>;

The specialization is enabled (20.14.18).

関連URL