yohhoyの日記

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

リテラル0との比較のみ許容する型

リテラル0との比較のみ許容する型の作り方。そのような型として、C++2a(C++20)三方比較演算子<=>の戻り値型(partial_ordering/ weak_ordering/strong_ordering)がある。

// C++2a
#include <cassert>
#include <compare>

int main()
{
  std::strong_ordering r = (108 <=> 42);
  assert(r > 0);  // OK
  assert(r > 1);  // NG: コンパイルエラー
}

リテラル0がstd::nullptr_t型の値(nullptr)に暗黙変換されることを利用する。

N4861 17.11.2.1/p1, p3より一部引用。

1 The types partial_ordering, weak_ordering, and strong_ordering are collectively termed the comparison category types. (snip)

3 The relational and equality operators for the comparison category types are specified with an anonymous parameter of unspecified type. This type shall be selected by the implementation such that these parameters can accept literal 0 as a corresponding argument. [Example: nullptr_t meets this requirement. --end example] In this context, the behavior of a program that supplies an argument other than a literal 0 is undefined.

関連URL