Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#include <iostream> // CRTP base that provides operator!= and operator> from operator== and operator< template<typename Derived> class Comparable { public: bool operator!=(const Derived& rhs) const { return !(static_cast<const Derived&>(*this) == rhs); } bool operator>(const Derived& rhs) const { return rhs < static_cast<const Derived&>(*this); } bool operator<=(const Derived& rhs) const { return !(static_cast<const Derived&>(*this) > rhs); } bool operator>=(const Derived& rhs) const { return !(static_cast<const Derived&>(*this) < rhs); } }; class Temperature : public Comparable<Temperature> { public: explicit Temperature(double celsius) : celsius_(celsius) {} bool operator==(const Temperature& rhs) const { return celsius_ == rhs.celsius_; } bool operator<(const Temperature& rhs) const { return celsius_ < rhs.celsius_; } double value() const { return celsius_; } private: double celsius_; }; int main() { Temperature t1(20.0), t2(35.0); std::cout << std::boolalpha; std::cout << "t1 < t2: " << (t1 < t2) << " "; // true std::cout << "t1 > t2: " << (t1 > t2) << " "; // false std::cout << "t1 != t2: " << (t1 != t2) << " "; // true std::cout << "t1 <= t2: " << (t1 <= t2) << " "; // true return 0; }
Result
Open