Advertisement
alansam

Using the [overloaded] spaceship [<=>] operator.

Jul 2nd, 2021 (edited)
1,158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4. #include <compare>
  5.  
  6. using namespace std::literals::string_literals;
  7.  
  8. class Stump {
  9. public:
  10.   Stump(int val = 0) : val_ { val } {};
  11.   Stump(Stump const & stmp) = default;
  12.   Stump(Stump && stmp) = default;
  13.   Stump & operator=(Stump const & stmp) = default;
  14.   Stump & operator=(Stump && stmp) = default;
  15.  
  16.   auto operator <=>(Stump const & that) const {
  17.     return val_ <=> that.val_;
  18.   }
  19.  
  20.   auto operator==(Stump const & that) const {
  21.     return val_ == that.val_;
  22.   }
  23.  
  24.   int val(int val) {
  25.     val_ = val;
  26.     return val_;
  27.   }
  28.  
  29.   int val(void) const {
  30.     return val_;
  31.   }
  32.  
  33. private:
  34.   int val_;
  35. };
  36.  
  37. int main() {
  38.   std::cout << "C++ Version: "s << __cplusplus << std::endl;
  39.  
  40.   int av;
  41.   int bv;
  42.   std::cout << "Enter two integer values: "s;
  43.   std::cout.flush();
  44.   std::cin >> av >> bv;
  45.   std::cout << std::endl;
  46.   std::cout << "Input: "s << av << ' ' << bv << '\n';
  47.  
  48.   auto ay = Stump(av);
  49.   auto be = Stump(bv);
  50.  
  51.   std::cout << ay.val() << " is"s
  52.             << ((ay < be) ? " less than "s :
  53.                 (ay > be) ? " greater than "s :
  54.                             " equal to "s)
  55.             << be.val()
  56.             << std::endl;
  57.  
  58.   std::cout << ay.val() << " is"s
  59.             << ((ay <= be) ? " less than or equal to "s :
  60.                 (ay >= be) ? " greater than or equal to "s :
  61.                              " not LE and not GE to "s)
  62.             << be.val()
  63.             << std::endl;
  64.  
  65.   std::cout << ay.val() << " is"s
  66.             << ((ay != be) ? " not equal to "s :
  67.                 (ay == be) ? " equal to "s :
  68.                              " not NE and not EQ to "s)
  69.             << be.val()
  70.             << std::endl;
  71.  
  72.   return 0;
  73. }
  74.  
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement