![](/img/trans.png)
[英]How can I use std::regular/std::totally_ordered in C++20?
[英]Why does std::totally_ordered<float> return true?
cpp 参考( https://en.cppreference.com/w/cpp/concepts/totally_ordered )说std::totally_ordered<T>
仅在给定左值 a、b 和 c 的情况下const std::remove_reference_t<T>
:
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 的concept
特征可以检测到这些。
概念也有语义要求,即对表达式含义的要求,可能是相对于彼此而言的。 concept
特征不能(通常)检测到这些。 如果一个类型同时满足句法和语义要求,就可以说它“建模”了一个概念。
对于totally_ordered
, float
满足概念的句法要求,但 IEEE754 float 它不满足语义要求。 实际上,C++20 使用totally_ordered<float>
作为这种语法与语义划分的示例。
一些concept
试图通过要求用户明确选择加入语义要求来解决这个问题。 但是, totally_ordered
不是其中之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.