Using the templates for overloaded comparison operators for Pool objects - C++ template

C++ examples for template:template class

Description

Using the templates for overloaded comparison operators for Pool objects

Demo Code

#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <iostream>

class  Pool/*  w w  w . j a v  a2 s.c  o  m*/
{
private:
  double length {1.0};
  double width {1.0};
  double height {1.0};

public:
  // Constructors
  Pool(double lv, double wv, double hv) : length {lv}, width {wv}, height {hv} {}

  Pool() {}                                                             // No-arg constructor

  Pool(const Pool& pool)                                                  // Copy constructor
    : length {pool.length}, width {pool.width}, height {pool.height} {}

  double volume() const                                                // Function to calculate the volume
  {
    return length*width*height;
  }

  // Accessors
  double getLength() const { return length; }
  double getWidth() const { return width; }
  double getHeight() const { return height; }

  bool operator<(const Pool& aPool) const;                               // Less-than operator
  bool operator<(double aValue) const;                                 // Compare Pool volume < double value

  // Equality operator
  bool operator==(const Pool& aPool) const
  {
    return volume() == aPool.volume();
  }

};

// Less-than comparison for Pool objects
inline bool Pool::operator<(const Pool& aPool) const
{
  return volume() < aPool.volume();
}

// Compare the volume of a Pool object with a constant
inline bool Pool::operator<(double aValue) const
{
  return volume() < aValue;
}

// Function comparing a constant with volume of a Pool object
inline bool operator<(double aValue, const Pool& aPool)
{
  return aValue < aPool.volume();
}

using namespace std::rel_ops;

void show(const Pool& pool1, const std::string relationship, const Pool& pool2)
{
  std::cout << "Pool " << pool1.getLength() << "x" << pool1.getWidth() << "x" << pool1.getHeight()
    << relationship
    << "Pool " << pool2.getLength() << "x" << pool2.getWidth() << "x" << pool2.getHeight()
    << std::endl;
}

int main()
{
  std::vector<Pool> pools {Pool {2.0, 2.0, 3.0}, Pool {1.0, 3.0, 2.0},
    Pool {1.0, 2.0, 1.0}, Pool {2.0, 3.0, 3.0}};

  Pool thePool {3.0, 1.0, 3.0};

  for (auto& pool : pools)
    if (thePool > pool) show(thePool, " is greater than ", pool);

  std::cout << std::endl;
  for (auto& pool : pools)
    if (thePool != pool) show(thePool, " is not equal to ", pool);

  std::cout << std::endl;
  for (int i {}; i < pools.size() - 1; ++i)
    for (int j {i + 1}; j < pools.size(); ++j)
    {
      if (pools[i] <= pools[j])
        show(pools[i], " less than or equal to ", pools[j]);
    }
}

Result


Related Tutorials