Another typedef usage example
bearophile
bearophileHUGS at lycos.com
Wed May 5 16:39:50 PDT 2010
Another usage example of the strong typedef of D1. This his D2 code, it shows how it can catch bugs in combineRectangles():
import std.algorithm: max, min;
typedef int Length;
typedef Length HorizPosition;
typedef Length VertPosition;
struct Point {
HorizPosition x;
VertPosition y;
}
struct Rectangle {
Point upperLeft, lowerRight;
}
// Length is defined as a generic form of HorizPosition and VertPosition
// because of the typedefs. There is no problem when combining a
// generic type with a type lower on the hierarchy.
Length perimeter(const ref Rectangle r) {
// Length len = 2 * (r.upperLeft.y - r.lowerRight.y); // problem
Length len = 0;
len += 2 * (r.upperLeft.y - r.lowerRight.y); // combining VertPosition with Length
len += 2 * (r.lowerRight.x - r.upperLeft.x); // combining HorizPosition with Length
return len;
}
/// To form one large rectangle that will just cover the rectangles r1 and r2.
Rectangle combineRectangles(const ref Rectangle r1, const ref Rectangle r2) {
return Rectangle(Point(min(r1.upperLeft.x, r2.upperLeft.x),
max(r1.upperLeft.y, r2.upperLeft.y)),
// Here HorizPosition and VertPosition need to be
// treated as two separate and distinct types
Point(max(r1.lowerRight.y, r2.lowerRight.x), // Err
min(r1.lowerRight.x, r2.lowerRight.x))); // Err
}
void main() {}
Bye,
bearophile
More information about the Digitalmars-d
mailing list