In this example, we will show you how to use a proxy object in order to postpone, or even avoid, using the computationally heavy std::sqrt() method when comparing the distance between two dimensional points.
Postponing an sqrt computation when comparing distances
A simple two-dimensional point class
Let's start with a simple point class in 2D. It has x and y coordinates and a member function, which calculates the distance to another point:
class Point{
public:
Point(float x, float y) : x_{x}, y_{y} {}
auto distance(const Point& p) const {
auto dist_sqrd = std::pow(x_-p.x_, 2) + std::pow(y_-p.y_, 2)
return std::sqrt(dist_sqrd);
}
private:
float x_{};
float y_{};
};
A simple usage example would be as follows...