Static indexing
Ali Cehreli
acehreli at yahoo.com
Wed Jan 12 15:39:09 UTC 2022
On 1/12/22 00:59, JG wrote:
> I want to make a type which has two fields x and y but can
> also be indexed with [0] and [1] checked at compile time.
std.typecons.Tuple already does that. You can add "member functions"
like foo() below by taking advantage of UFCS:
import std.typecons;
alias Point = Tuple!(double, "x", double, "y");
unittest
{
Point p = Point(1.25,3.5);
assert(p[0]==1.25);
assert(p.x==1.25);
assert(p[1]==3.5);
assert(p.y==3.5);
assert(!__traits(compiles,Point.init[3]));
}
void foo(ref Point p) {
p.x += p.y;
}
unittest {
auto p = Point(1.5, 2.75);
p.foo();
assert(p.x == 4.25);
assert(p.y == 2.75);
}
void main() {
}
Also note, I changed all the floating point values to ones that can be
fully representable by floating point types so that the unit tests would
always succeed. (For example, 0.1 and 0.4 etc. cannot be represented
fully but 0.5 and 0.25 etc. can be.)
Ali
More information about the Digitalmars-d-learn
mailing list