代码之家  ›  专栏  ›  技术社区  ›  Piotr Siupa

如何在switch语句中使用太空船操作员

  •  3
  • Piotr Siupa  · 技术社区  · 2 年前

    新的 <=> 运算符使编写代码更加方便,并且如果比较算法是非平凡的,它可以节省一些性能,因为它不需要重复两次就可以获得完整的排序。

    或者至少当我知道这件事的时候我是这么想的。 然而,当我尝试在实践中使用它时 switch 声明,它不起作用。

    此代码无法编译:

    #include <iostream>
    
    void compare_values(int x, int y)
    {
        switch (x <=> y)
        {
        case std::strong_ordering::less:
            std::cout << "is less\n";
            break;
        case std::strong_ordering::greater:
            std::cout << "is greater\n";
            break;
        case std::strong_ordering::equal:
            std::cout << "is equal\n";
            break;
        }
    }
    

    编译器显示一个错误,表明 <=> 不能在中使用 转换 :

    <source>: In function 'void compare_values(int, int)':
    <source>:5:15: error: switch quantity not an integer
        5 |     switch (x <=> y)
          |             ~~^~~~~
    Compiler returned: 1
    

    ( live example )

    我想,在switch中使用太空船操作员是一个非常基本、明显和常见的用例,所以可能有一些技巧可以让它发挥作用。不过,我无法理解。

    如何修复此代码?

    1 回复  |  直到 2 年前
        1
  •  3
  •   Nicol Bolas    2 年前

    飞船操作员返回 std::strong_ordering 它不是积分类型,因此不能用于 switch-case 陈述

    你可以在 if-else 语句。

    如果您喜欢使用 开关箱 ,可以使用一个琐碎的实用程序来转换 std::strong_ordering 到具有一些预定义值的积分类型。
    在这种情况下,返回-1/0/1将是非常自然的:

    #include <iostream>
    
    constexpr int strong_ordering_to_int(std::strong_ordering o)
    {
        if (o == std::strong_ordering::less)    return -1;
        if (o == std::strong_ordering::greater) return 1;
        return 0;
    }
    
    void compare_values(int x, int y)
    {
        switch (strong_ordering_to_int(x <=> y))
        {
        case -1:
            std::cout << "is less\n";
            break;
        case 1:
            std::cout << "is greater\n";
            break;
        case 0:
            std::cout << "is equal\n";
            break;
        }
    }
    
    int main()
    {
        compare_values(2, 3);
        compare_values(3, 2);
        compare_values(3, 3);
    }
    

    输出

    is less
    is greater
    is equal
    

    Live demo

    推荐文章