Struct and Class Templates
You will learn about structs and class templates in this lesson.
We'll cover the following...
The Point
struct may be seen as having a limitation. Because its two members are defined specifically as int
, it cannot represent fractional coordinate values. This limitation can be removed if the Point
struct is defined as a template.
Let’s first add a member function that returns the distance to another Point
object:
Press + to interact
import std.math;// ...struct Point {int x;int y;int distanceTo(Point that) const {immutable real xDistance = x - that.x;immutable real yDistance = y - that.y;immutable distance = sqrt((xDistance * xDistance) +(yDistance * yDistance));return cast(int)distance;}}void main() {}
That definition of Point
is suitable when the required precision is relatively low: It can calculate the distance between two points at kilometer precision, e.g., between the center and branch offices of an organization: