C++ vs D: Default param values and struct to array casting
Paul Backus
snarwin at gmail.com
Fri Sep 6 16:20:15 UTC 2019
On Friday, 6 September 2019 at 09:28:57 UTC, Andrew Edwards wrote:
> This is my thought on how to accomplish op overloading:
>
> struct Test
> {
> float a, b, c, d;
> float opIndex(size_t i)
> in(i >= 0 && i <= 3)
> {
> final switch(i)
> {
> case 0: return a;
> case 1: return b;
> case 2: return c;
> case 3: return b;
> }
> }
>
> void opIndexAssign(float val, size_t i)
> in(i >= 0 && i <= 3)
> {
> final switch(i)
> {
> case 0: a = val; break;
> case 1: b = val; break;
> case 2: c = val; break;
> case 3: d = val; break;
> }
> }
> }
>
> Please advise if I've gone off the beaten path. It seems
> overkill for the two lines of code C++ requires so any
> suggestion is greatly appreciated.
You can use `static foreach` to eliminate the repetition in the
switch statements. For example:
float opIndex(size_t i)
in (i < typeof(this).tupleof.length)
{
final switch (i) {
static foreach (fid, field; typeof(this).tupleof) {
case fid: return field;
}
}
}
More information about the Digitalmars-d-learn
mailing list