Kyl*_*and 5 c++ comparison-operators c++11
如果我有一个由单个数字数据成员(例如,一个int)和各种方法组成的类型,是否有一种方便的方法来告诉编译器自动生成所有明显的比较运算符?
即,而不是这个(当然使用inline而不是constexprC++ 03):
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
}
Run Code Online (Sandbox Code Playgroud)
我想要像Ruby的Comparable mixin这样的东西,它基本上允许你定义一个操作符,让Ruby来处理其余的操作.我甚至认为编译器生成的版本可能比我的更好:应该rhs是const每个案例的参考?我应该定义转发引用的版本吗?如果我忘了其中一个操作员怎么办?等等.
所以...这样的事情存在吗?
(请原谅我,如果这是重复的;我认为有人会在某个地方问这个,因为它似乎是一个明显的功能,但我找不到任何东西.)
编辑:自动生成比较运算符已被提议作为一项功能:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3950.html
Die*_*ühl 11
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));
}
Run Code Online (Sandbox Code Playgroud)