Nhiệm vụ thường xuyên của tôi là viết tất cả toán tử so sánh quá tải cho một lớp, vì vậy tôi đã viết một lớp mẫu thực hiện <, < =,> =,! = Nếu lớp dẫn xuất thực hiện == và <. Nó đang làm việc nhưng tính năng rất nhiều diễn viên và không rõ ràng là "mẫu kỳ lạ mẫu định kỳ", vì vậy tôi tự hỏi, nếu có những giải pháp đơn giản?Lớp mẫu thực hiện toán tử so sánh
template <class Derived>
class Comparable
{
public:
bool operator!=(const Comparable<Derived>& other) {
return !(static_cast<Derived*>(this)->operator==
(*static_cast<const Derived*>(&other)));
}
bool operator<=(const Comparable<Derived>& other) {
return (static_cast<Derived*>(this)->operator==
(*static_cast<const Derived*>(&other)))
|| (static_cast<Derived*>(this)->operator<
(*static_cast<const Derived*>(&other)));
}
bool operator>(const Comparable<Derived>& other) {
return !(static_cast<Derived*>(this)->operator==
(*static_cast<const Derived*>(&other)))
&& !(static_cast<Derived*>(this)->operator<
(*static_cast<const Derived*>(&other)));
}
bool operator>=(const Comparable<Derived>& other) {
return !(static_cast<Derived*>(this)->operator<
(*static_cast<const Derived*>(&other)));
}
};
http://www.boost.org/doc/libs/1_58_0/libs/utility/operators.htm – interjay
Có. Tôi đã đề xuất một giải pháp tương tự cho những gì @interjay liên kết ở trên: định nghĩa hàm friend bên trong một lớp là * inline * d các hàm miễn phí có thể được tìm thấy thông qua ADL trên kiểu có nguồn gốc. Bạn có thể sử dụng nó để cung cấp cho các toán tử bạn cần. –