为什么 std::optional 对 std::nullopt 类型的操作数有一个特殊的相等运算符

问题描述

类模板 std::optional 具有转换构造函数

constexpr optional(nullopt_t) noexcept;

那么问题来了,为什么在 C++ 标准中声明了特殊的单一相等运算符

template<class T> constexpr bool operator==(const optional<T>&,nullopt_t) noexcept;

std::nullopt 仅用作第二个操作数时?

(例如参见 C++ 20 Draft N 4860

// 20.6.7,comparison with nullopt
template<class T> constexpr bool operator==(const optional<T>&,nullopt_t) noexcept;

)

引入这个特殊运算符的原因是什么?

解决方法

您正在查看 C++20 草案。不迟于 N4820 的草稿具有所有相等运算符。由于 rewritten candidates 的引入,它们后来 [可能] 被删除。