为什么 std::totally_ordered<float> 返回 true?



cpp引用(https://en.cppreference.com/w/cpp/concepts/totally_ordered)表示std::totally_ordered<T>仅当给定const std::remove_reference_t<T>:类型的左值a、b和c时才建模

  • bool(a < b)bool(a > b)bool(a == b)中恰好有一个为真
  • 如果bool(a < b)bool(b < c)都为真,则bool(a < c)为真
  • bool(a > b) == bool(b < a)
  • bool(a >= b) == !bool(a < b)
  • bool(a <= b) == !bool(b < a)

所以我考虑了NaN,发现float与句子bool(a > b) == bool(b < a)不符。但std::totally_ordered<float>true。我做错什么了吗?

=======

我用这个宏创建NaN

#define NAN        ((float)(INFINITY * 0.0F))

这是我的代码:

#include <iostream>
#include <concepts>
using namespace std;
int main(int argc, char* argv[])
{
/*
1) std::totally_ordered<T> is modeled only if, given lvalues a, b and c of type const std::remove_reference_t<T>:
Exactly one of bool(a < b), bool(a > b) and bool(a == b) is true;
If bool(a < b) and bool(b < c) are both true, then bool(a < c) is true;
bool(a > b) == bool(b < a)
bool(a >= b) == !bool(a < b)
bool(a <= b) == !bool(b < a)
*/
constexpr bool b = totally_ordered<float>; // true
cout << typeid(NAN).name() << endl;        // float
cout << NAN << endl;
cout << b << endl;
cout << "Exactly one of bool(a < b), bool(a > b) and bool(a == b) is true;" << endl;
cout << (NAN < NAN) << endl;
cout << (NAN > NAN) << endl;
cout << (NAN == NAN) << endl;
cout << " If bool(a < b) and bool(b < c) are both true, then bool(a < c) is true;" << endl;
cout << (1.f < 2.f) << endl;
cout << (2.f < NAN) << endl;
cout << (1.f < NAN) << endl;
cout << "bool(a > b) == bool(b < a)" << endl; ////// IT IS FALSE //////
cout << (NAN > 1.f) << endl;
cout << (1.f < NAN) << endl;
cout << "bool(a >= b) == !bool(a < b)" << endl;
cout << (NAN >= 1.f) << endl;
cout << (NAN < 1.f) << endl;
cout << "bool(a <= b) == !bool(b < a)" << endl;
cout << (NAN <= 1.f) << endl;
cout << (NAN > 1.f) << endl;
cout << endl;
}

概念有语法要求,即存在一些表达式集,并且是提供特定行为的类型。C++20的CCD_ 18特性可以检测到这些。

概念也有语义要求,即关于表达式的含义的要求,可能是相对于彼此的。concept功能无法(通常(检测到这些。一种类型被称为";型号";一个概念,如果它同时满足语法和语义要求。

对于totally_orderedfloat满足概念的语法要求,但对于IEEE754浮点,它不满足语义要求。事实上,C++20使用totally_ordered<float>作为表示法中这种句法与语义划分的例子。

一些concept试图通过要求用户明确选择语义需求来解决这个问题。但totally_ordered不是其中之一。

相关内容

最新更新