c++ - `std::less` 是如何工作的?

标签 c++ c++11 stl relational partial-ordering

指针关系运算符不定义总顺序 ( § 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.h 来回答这个问题对于 struct 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(您在问题中引用的内容),在这方面的行为未指定

Unspecified behavior 在 §1.3.25 中定义为:

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

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

关于c++ - `std::less` 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30617158/

相关文章:

c++ - 使用指向 Value 的原始指针从 std::list<Value> 中删除?

c++ - ptmconvert (C/C++) 中的编译器错误

c++ - 初学者 C++ 继承

c++ - GCC C++ 编译器是否考虑了 __restrict - 语句?

c++ - localtime_s 和 strftime 用法构建 ISO 时间字符串

C++:std "magically"在那里吗?总是?

c++ - 如何在模板化类中声明模板化 map::iterator。下面的代码说;编译时预期

c++ - 无法在opencv中读取视频

c++ - 如何定义返回嵌套类对象的模板类成员函数

c++ - C++ 中的分配器用法(STL 树)