C++语言特性32 - 三方比较(C++20)

一:概述

在 C++20 中,引入了一个新的比较运算符 <=>。表达式形如 a <=> b,它的返回值不是简单的 bool,而是一个"比较结果对象"。(比较类别 --- comparison category object),根据 ab 的大小/相等关系,返回不同结果。具体来说:如果 a < b,那么 (a <=> b) < 0;如果 a > b,那么 (a <=> b) > 0;如果 a == b(或等价 / 相等 / 等价关系成立),那么 (a <=> b) == 0。

二:例子

cpp 复制代码
#include <iostream>
 
int main()
{
    static_assert(sizeof(unsigned char) < sizeof(int),
                  "Cannot compare signed and smaller unsigned properly");
    int a = -1;
    int b = 1;
    unsigned int c = 1;
    unsigned char d = 1;
 
    std::cout << std::boolalpha
              << "Comparing two signed values:\n"
                 " -1 == 1 ? " << (a == b) << "\n"
                 " -1 <  1 ? " << (a <  b) << "\n"
                 " -1 >  1 ? " << (a >  b) << "\n"
                 "Comparing signed and unsigned:\n"
                 // may issue different-signedness warning:
                 " -1 == 1 ? " << (a == c) << "\n"
                 // may issue different-signedness warning:
                 " -1 <  1 ? " << (a <  c) << "\n"
                 // may issue different-signedness warning:
                 " -1 >  1 ? " << (a >  c) << "\n"
                 "Comparing signed and smaller unsigned:\n"
                 " -1 == 1 ? " << (a == d) << "\n"
                 " -1 <  1 ? " << (a <  d) << "\n"
                 " -1 >  1 ? " << (a >  d) << '\n';
}
cpp 复制代码
#include <iostream>
 
struct Foo
{
    int n1;
    int n2;
};
 
union Union
{
    int n;
    double d;
};
 
int main()
{
    std::cout << std::boolalpha;
 
    char a[4] = "abc";
    char* p1 = &a[1];
    char* p2 = &a[2];
    std::cout << "Pointers to array elements:\n"
              << "p1 == p2? " << (p1 == p2) << '\n'
              << "p1 <  p2? " << (p1 <  p2) << '\n';
 
    Foo f;
    int* p3 = &f.n1;
    int* p4 = &f.n2;
    std::cout << "Pointers to members of a class:\n"
              << "p3 == p4? " << (p3 == p4) << '\n'
              << "p3 <  p4? " << (p3 <  p4) << '\n';
 
    Union u;
    int* p5 = &u.n;
    double* p6 = &u.d;
    std::cout << "Pointers to members of a union:\n"
              << "p5 == (void*)p6? " << (p5 == (void*)p6) << '\n'
              << "p5 <  (void*)p6? " << (p5 <  (void*)p6) << '\n';
}
相关推荐
老四啊laosi21 小时前
[C++进阶] 24. 哈希表封装unordered_map && unordered_set
c++·哈希表·封装·unordered_map·unordered_set
014-code1 天前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
妙为1 天前
银河麒麟V4下编译Qt5.12.12源码
c++·qt·国产化·osg3.6.5·osgearth3.2·银河麒麟v4
lly2024061 天前
组合模式(Composite Pattern)
开发语言
游乐码1 天前
c#泛型约束
开发语言·c#
Dontla1 天前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen1 天前
python rest请求、requests
开发语言·python
铁东博客1 天前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui1 天前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳1 天前
Python从入门到精通day63
开发语言·python