Annoyance with new integer promotion deprecations
Luís Marques
luis at luismarques.eu
Wed Feb 7 01:06:42 UTC 2018
On Wednesday, 7 February 2018 at 00:24:26 UTC, H. S. Teoh wrote:
> I really like your .nx idea! It neatly sidesteps the
> nonsensical mandatory casts and on top of that documents intent
> (the .nx being a telltale sign of truncation -- much better
> than arbitrary implicit rules). I think I'll adopt it in some
> form in my code, to make dealing with narrow ints saner. I
> don't know what your .nx type does, but for my purposes I'll
> probably just have a thin wrapper around byte/ubyte/etc. with
> overloaded arithmetic operators that perform the requisite
> casts.
Yeah, it's just a thin wrapper. I implemented just enough to
cover my use cases but just in case it's useful to you or someone
else, here goes my implementation...
private struct NX(T)
{
T value;
alias value this;
this(T value)
{
this.value = value;
}
NX!T opUnary(string s)()
{
return NX!T(cast(T) mixin(s ~ "value"));
}
auto opBinary(string op, U)(NX!U rhs)
{
static if(rhs.value.sizeof > value.sizeof)
return mixin("rhs " ~ op ~ " value");
else
return NX!T(cast(T) mixin("value " ~ op ~ " rhs"));
}
NX!T opBinary(string op)(T rhs)
{
return NX!T(cast(T) mixin("value " ~ op ~ " rhs"));
}
}
alias i16 = NX!short;
alias u16 = NX!ushort;
alias i8 = NX!byte;
alias u8 = NX!ubyte;
auto nx(byte v)
{
return i8(v);
}
auto nx(ubyte v)
{
return u8(v);
}
auto nx(short v)
{
return i16(v);
}
auto nx(ushort v)
{
return u16(v);
}
auto nx(int v)
{
return i16(cast(short) v);
}
auto nx(uint v)
{
return u16(cast(ushort) v);
}
Those last two nx() probably won't make sense outside of my
16-bit target (even though I build the same code for 32 bits too,
to run the tests on my x86 host).
If you start using something like this in your code please send
me a link, so I can copy a better implementation :-)
More information about the Digitalmars-d
mailing list