リテラル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
)に暗黙変換されることを利用する。
- GCC/libstdc++-v3: https://github.com/gcc-mirror/gcc/blob/releases/gcc-10/libstdc++-v3/libsupc++/compare#L57
- Clang/libcxx: https://github.com/llvm/llvm-project/blob/llvmorg-10.0.0/libcxx/include/compare#L79
- MSVC: https://github.com/microsoft/STL/blob/12c684bba78f9b032050526abdebf14f58ca26a3/stl/inc/compare#L29
N4861 17.11.2.1/p1, p3より一部引用。
1 The types
partial_ordering
,weak_ordering
, andstrong_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 literal0
is undefined.
関連URL