gpt4 book ai didi

c++ - boost `less_than` 两种版本的实现

转载 作者:太空宇宙 更新时间:2023-11-04 12:10:34 26 4
gpt4 key购买 nike

基于 pp130

However, it would be nice to also have a version that supports comparisons between T and compatible types, which is simply a case of adding more overloads. For symmetry, you need to allow either type to be on the left side of the operation. (This is easy to forget when adding operators manually; one tends to only see clearly the fact that the right side must accept the other type. Of course, your two-type version of less_than wouldn't make such silly mistakes, right?)

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&)没有意义(甚至是错误的)。

同样适用于第二个重载。

关于c++ - boost `less_than` 两种版本的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10055374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com