gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:56:45 26 4
gpt4 key购买 nike

指针关系运算符不定义总顺序 ( § 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com