`std::less` 是如何工作的?

How does `std::less` work?

指针关系运算符未定义全序(§ 5.9 of the C++11 standard):

If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of p<q, p>q, p<=q, and p>=q are unspecified.

std::less 文档说:

The partial specialization of std::less for any pointer type yields a total order, even if the built-in operator< does not.

它如何从部分订单中产生这个总订单?


我无法通过查看 /usr/include/c++/4.9/bits/stl_function.hstruct less 定义来回答这个问题:

  template<typename _Tp = void>
    struct less;

  template<typename _Tp>
    struct less : public binary_function<_Tp, _Tp, bool>
    {
      bool
      operator()(const _Tp& __x, const _Tp& __y) const
      { return __x < __y; }
    };

  template<>
    struct less<void>
    {
      template <typename _Tp, typename _Up>
        auto
        operator()(_Tp&& __t, _Up&& __u) const
        noexcept(noexcept(std::forward<_Tp>(__t) < std::forward<_Up>(__u)))
        -> decltype(std::forward<_Tp>(__t) < std::forward<_Up>(__u))
        { return std::forward<_Tp>(__t) < std::forward<_Up>(__u); }

      typedef __is_transparent is_transparent;
    };

How does it yield this total order from a partial order?

标准很少说明如何应该完成某事。相反,它说明了需要什么。事实确实如此。该标准要求 std::less 提供总订单,在 §20.9.6/14:

For templates greater, less, greater_equal, and less_equal, the specializations for any pointer type yield a total order, even if the built-in operators <, >, <=, >= do not.

operator< 在这方面的行为是 未指定的 根据 §5.9/4(您在问题中引用的内容)。

未指定的行为 在 §1.3.25 中定义为:

behavior, for a well-formed program construct and correct data, that depends on the implementation [...]

在你的具体实现中,operator<已经提供了总序(可能是因为你的指针类型实现为32位或64位地址,很容易理解为类似于无符号整数的东西,产生总顺序),因此 std::less 只是将其参数转发给该运算符。