...

/

Solution: Extend MyInt Class

Solution: Extend MyInt Class

The solution to the challenge, 'Exercise: Extend MyInt Class'.

We'll cover the following...

Solution

Press + to interact
#include <compare>
#include <iostream>
class MyInt {
public:
constexpr explicit MyInt(int val): value{val} { }
auto operator<=>(const MyInt& rhs) const = default;
constexpr auto operator<=>(const int& rhs) const {
return value <=> rhs;
}
private:
int value;
};
template<typename T,typename T2>
constexpr bool isLessThan(const T& lhs,const T2& rhs) {
return lhs < rhs;
}
int main() {
std::cout << std::boolalpha << '\n';
constexpr MyInt myInt2011(2011);
constexpr MyInt myInt2014(2014);
constexpr int int2011(2011);
constexpr int int2014(2014);
std::cout << "isLessThan(myInt2011, myInt2014): "
<< isLessThan(myInt2011, myInt2014) << '\n';
std::cout << "isLessThan(int2011, myInt2014): "
<< isLessThan(int2011, myInt2014) << '\n';
std::cout << "isLessThan(myInt2011, int2014): "
<< isLessThan(myInt2011, int2014) << '\n';
constexpr auto res = isLessThan(myInt2011, int2014);
std::cout << '\n';
}

I defined the three-way comparison operator (line 8) and declared it constexpr. The user-defined three-way comparison operator is not implicitly constexpr, unlike the compiler-generated three-way comparison operator. The comparison of MyInt and int is possible in each combination (lines 30, 33, and 36).

Honestly, the implementation of the various three-way comparison operators is very elegant. The compiler auto-generates the comparison of MyInt ...