C++ 中的两个比较运算符,如 python
Two comparison operators in c++ like python
比较 5 > x > 1
在 C++ 中是否有效,就像在 python 中一样。它没有显示任何编译错误,但似乎也不起作用。
在 C++ 中,5 > x > 1
分组为 (5 > x) > 1
。
(5 > x)
是 false
或 true
,因此永远不会大于 1,因为 false
和 true
转换为 0
和 1
分别。因此
5 > x > 1
对于 x
的任何值, 在 C++ 中是 false
。所以在 C++ 中你需要用更长的形式编写你真正想要的表达式
x > 1 && x < 5
我从不满足于你不能选项...所以理论上你可以像这样重载运算符(只是一个素描,但我想你会明白重点的):
#include <iostream>
template <class T>
struct TwoWayComparison {
T value;
bool cond = true;
friend TwoWayComparison operator >(const T& lhs, const TwoWayComparison& rhs) {
return {rhs.value, lhs > rhs.value};
}
friend TwoWayComparison operator >(const TwoWayComparison& lhs, const T& rhs) {
return {rhs, lhs.cond && lhs.value > rhs};
}
operator bool() {
return cond;
}
};
int main() {
TwoWayComparison<int> x{3};
if (15 > x > 1) {
std::cout << "abc" << std::endl;
}
}
比较 5 > x > 1
在 C++ 中是否有效,就像在 python 中一样。它没有显示任何编译错误,但似乎也不起作用。
在 C++ 中,5 > x > 1
分组为 (5 > x) > 1
。
(5 > x)
是 false
或 true
,因此永远不会大于 1,因为 false
和 true
转换为 0
和 1
分别。因此
5 > x > 1
对于 x
的任何值, 在 C++ 中是 false
。所以在 C++ 中你需要用更长的形式编写你真正想要的表达式
x > 1 && x < 5
我从不满足于你不能选项...所以理论上你可以像这样重载运算符(只是一个素描,但我想你会明白重点的):
#include <iostream>
template <class T>
struct TwoWayComparison {
T value;
bool cond = true;
friend TwoWayComparison operator >(const T& lhs, const TwoWayComparison& rhs) {
return {rhs.value, lhs > rhs.value};
}
friend TwoWayComparison operator >(const TwoWayComparison& lhs, const T& rhs) {
return {rhs, lhs.cond && lhs.value > rhs};
}
operator bool() {
return cond;
}
};
int main() {
TwoWayComparison<int> x{3};
if (15 > x > 1) {
std::cout << "abc" << std::endl;
}
}