作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
如果我有一个由单个数字数据成员(例如,int
)和各种方法组成的类型,是否有一种方便的方法告诉编译器自动生成所有明显的比较运算符?
即,代替这个(对于 C++03,当然使用 inline
而不是 constexpr
):
class MyValueType
{
private:
int myvalue;
public:
constexpr bool operator<(MyValueType rhs) const { return myvalue < rhs.myvalue; }
constexpr bool operator>(MyValueType rhs) const { return myvalue > rhs.myvalue; }
constexpr bool operator>=(MyValueType rhs) const { return myvalue >= rhs.myvalue; }
constexpr bool operator==(MyValueType rhs) const { return myvalue == rhs.myvalue; }
/// .... etc
}
我想要像 Ruby 的 Comparable mixin 这样的东西,它基本上允许您定义一个 运算符,让 Ruby 处理其余的。而且我什至假设编译器生成的版本可能会比我的更好:rhs
应该是每个案例的 const
ref 吗?我应该定义采用转发引用的版本吗?如果我忘记了其中一位接线员怎么办?等等
那么...这样的事情是否存在?
(如果这是重复的,请原谅我;我假设有人已经在某个地方问过这个问题,因为它似乎是一个明显需要的功能,但我找不到。)
编辑:自动生成比较运算符已被提议作为一项功能:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3950.html
最佳答案
执行此操作的 C++ 方法是使用标记类型和 ADL。这是一个简单的例子:
namespace relational {
struct tag {};
template <typename T>
bool operator== (T const& lhs, T const& rhs) { return !(rhs < lhs) && !(lhs < rhs); }
template <typename T>
bool operator!= (T const& lhs, T const& rhs) { return !(lhs == rhs); }
template <typename T>
bool operator> (T const& lhs, T const& rhs) { return rhs < lhs; }
template <typename T>
bool operator<= (T const& lhs, T const& rhs) { return !(rhs < lhs); }
template <typename T>
bool operator>= (T const& lhs, T const& rhs) { return !(lhs < rhs); }
}
struct foo: relational::tag {
int value;
foo(int value): value(value) {}
bool operator< (foo const& other) const { return this->value < other.value; }
};
#include <iostream>
void compare(foo f0, foo f1) {
std::cout << std::boolalpha
<< f0.value << " == " << f1.value << " => " << (f0 == f1) << '\n'
<< f0.value << " != " << f1.value << " => " << (f0 != f1) << '\n'
<< f0.value << " < " << f1.value << " => " << (f0 < f1) << '\n'
<< f0.value << " <= " << f1.value << " => " << (f0 <= f1) << '\n'
<< f0.value << " > " << f1.value << " => " << (f0 > f1) << '\n'
<< f0.value << " >= " << f1.value << " => " << (f0 >= f1) << '\n'
;
}
int main() {
compare(foo(1), foo(2));
compare(foo(2), foo(2));
}
关于c++ - 使用一个数字数据成员为类定义所有比较运算符的便捷方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29269124/
我是一名优秀的程序员,十分优秀!