实现两种类型的提升“less_than”

Implementation of two-type version of boost `less_than`

本文关键字:less than 两种 类型 实现      更新时间:2023-10-16

基于 pp130

但是,最好也有一个支持 T 和兼容类型之间的比较,这只是一个案例 添加更多重载。对于对称性,您需要允许任一类型 位于操作的左侧。(这很容易忘记 手动添加运算符;人们往往只能清楚地看到这样一个事实: 右侧必须接受另一种类型。当然,你的两种类型 less_than的版本不会犯这种愚蠢的错误,对吧?

template <class T,class U>
class less_than2
{
public:
  friend bool operator<=(const T& lhs,const U& rhs) { 
    return !(lhs>rhs); 
  }
  friend bool operator>=(const T& lhs,const U& rhs) { 
    return !(lhs<rhs); 
  }
  friend bool operator>(const U& lhs,const T& rhs) {
    return rhs<lhs; 
  }
  friend bool operator<(const U& lhs,const T& rhs)  { 
    return rhs>lhs; 
  }
  friend bool operator<=(const U& lhs,const T& rhs) { 
    return !(rhs<lhs); 
  }
  friend bool operator>=(const U& lhs,const T& rhs) { 
    return !(rhs>lhs); 
  }
};

>为什么我们不必提供以下两个功能?

  friend bool operator>(const T& lhs,const U& rhs) {
    return rhs<lhs; 
  }
  friend bool operator<(const T& lhs,const U& rhs)  { 
    return rhs>lhs; 
  }

此运算符:

friend bool operator>=(const T& lhs,const U& rhs) { 
  return !(lhs<rhs); 
}

取决于函数调用lhr<rhs的有效性。由您的operator<(const T&, const U&)第二次提供其签名是没有意义的(甚至是错误的)。

这同样适用于第二次重载。