Integer promotion issue
Steven Schveighoffer
schveiguy at gmail.com
Sun Jan 26 00:31:03 UTC 2020
On 1/25/20 7:07 PM, Evan wrote:
> On Saturday, 25 January 2020 at 23:58:00 UTC, Steven Schveighoffer wrote:
>> On 1/25/20 6:46 PM, Evan wrote:
>>> [...]
>>
>> Not really. You can cast yourself, write your own type that does it,
>> or use masking to have the compiler accept the result (i.e. (a + b) &
>> 0xff).
>>
>> I'd recommend your own type, as it will look a lot cleaner.
>>
>
> If I make my own type then I have to write more casts from my type to
> built in types. I want to create less work for myself not more.
I'm not sure what you mean. You should be able to alias-this the type to
reduce the casting. Whipped up in a couple minutes:
struct U8
{
ubyte _val;
alias _val this;
this(ubyte x)
{
_val = x;
}
U8 opBinary(string op, T)(T other)
if ((is(T == U8) || is(T == ubyte)) && (op == "+" || op ==
"-" /* || op == ... */))
{
return mixin("U8(cast(ubyte)(_val " ~ op ~ " cast(ubyte)other))");
}
// opBinaryRight etc...
}
void main()
{
import std.stdio;
U8 a = 0x01;
U8 b = 0x01;
ubyte c = a + b; //Error: cannot implicitly convert expression
cast(int)a + cast(int)b of type int to ubyte
writeln(c); // 2
ubyte d = b - a;
writeln(d); // 0
writeln(a); // 1 (uses alias this)
}
-Steve
More information about the Digitalmars-d
mailing list