C++
Beginner
1 min read
Compile-Time Polymorphism with CRTP
Example
#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) << "\n"; // true
std::cout << "t1 > t2: " << (t1 > t2) << "\n"; // false
std::cout << "t1 != t2: " << (t1 != t2) << "\n"; // true
std::cout << "t1 <= t2: " << (t1 <= t2) << "\n"; // true
return 0;
}