c++ - 三向比较运算符的顺序推导不一致

标签 c++ qt c++20 return-type-deduction spaceship-operator

前一段时间,我定义了我的第一个三向比较运算符。它比较了单个类型并替换了多个常规运算符。很棒的功能。然后,我尝试实现一个类似的运算符,以通过委派比较两个变体:

auto operator <=> (const QVariant& l, const QVariant& r)
{   
   switch (l.type())
   {
      case QMetaType::Int:
         return l.toInt() <=> r.toInt();
      case QMetaType::Double:
         return l.toDouble() <=> r.toDouble();
      default:
         throw;
   }
}
这没有编译,我得到了错误

inconsistent deduction for auto return type: ‘std::strong_ordering’ and then ‘std::partial_ordering’.


显然,intdouble spaceship 运算符(operator)返回不同的类型。
解决此问题的正确方法是什么?

最佳答案

operator<=>intdouble的类型不同,但是应该具有相同的类型。您可能想利用编译器自动查找正确的类型。您可以使用std::common_type来执行此操作,但这将非常难看。仅在(在库中而不是在编译器中实现时)利用std::common_type类型的作用并使用三元运算符会更容易:

auto operator <=> (const QVariant& l, const QVariant& r)
{   
    return l.type() == QMetaType:Int? l.toInt() <=> r.toInt()
         : l.type() == QMetaType::Double? l.toDouble() <=> r.toDouble()
         : throw;
}

关于c++ - 三向比较运算符的顺序推导不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65363107/

相关文章:

c++ - 为什么 std::ranges::views::filter 不能将 std::isupper 作为参数?

c++ - 刷新 Qt 表单 - 似乎卡住了

c++ - 如何使用折叠表达式调用成员函数链

c++ - 将 ISO8601 字符串转换为自纪元以来的毫秒数

c++ 写运算符>,我似乎不正确地接近比较,我该如何正确地做到这一点?

c++ - QPushButton 用法

c++ - 为什么 ball1.boundingrect.center 返回与 ball2.boundingrect.center 相同的值?

c++ - 除了概念之外,C++20 中还有其他 void_t 替代品吗?

c++ - 模板中的关键字 "typename"

c++ - 模板结构中的重载运算符