January 2019
Intermediate to advanced
512 pages
14h 5m
English
Let's consider several examples where CRTP is used to delegate behavior from the base class to the derived one.
The first example is a very simple one—for any class that provides operator==(), we want to generate operator!=() automatically as the inverse of the former:
template <typename D> struct not_equal { bool operator!=(const D& rhs) const { return !static_cast<const D*>(this)->operator==(rhs); }};class C : public not_equal<C> { int i_; public: C(int i) : i_(i) {} bool operator==(const C& rhs) const { return i_ == rhs.i_; }};
Any class that inherits from not_equal in this manner automatically acquires the not equal operator that is guaranteed to match the provided operator, equal. An observant reader might point ...
Read now
Unlock full access