mercredi 3 juin 2015

How does `std::less` work?

Pointer relational operators do not define a total order (§ 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 documentation says:

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

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


I am unable to answer to this question looking at /usr/include/c++/4.9/bits/stl_function.h for struct less definitions:

  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;
    };

Aucun commentaire:

Enregistrer un commentaire