ushort + ushort = int?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Aug 20 10:50:35 UTC 2018


On Monday, August 20, 2018 4:29:56 AM MDT Andrey via Digitalmars-d-learn 
wrote:
> On Monday, 20 August 2018 at 09:56:13 UTC, Jonathan M Davis wrote:
> > It's a combination of keeping the C semantics (in general, C
> > code is valid D code with the same semantics, or it won't
> > compile) and the fact that D requires casts for narrowing
> > conversions. When you add two shorts in C/C++, it converts them
> > to int just like D does. It's just that C/C++ has implicit
> > narrowing casts, so if you assign the result to a short, it
> > then converts the result to short even if that means that the
> > value could be truncated, whereas D requires that you
> > explicitly cast to convert to int rather than silently
> > truncating.
> >
> > It does prevent certain classes of problems (e.g. there are
> > plenty of bugs in C/C++ due to implicit narrowing conversions),
> > but it can also get pretty annoying if you're doing much math
> > on integer types smaller than int, and you either know that
> > they aren't going to overflow or truncate, or you don't care
> > that they will. But if you're only doing math on such small
> > integeral types occasionally, then it pretty much just means
> > that once in a while, you get briefly annoyed when you forget
> > to add a cast, and the compiler yells at you.
> >
> > - Jonathan M Davis
>
> Understood.
> Is there a workaround to reduce amount of manual casts of input
> types T into output T?
> May be one can write some module-global operator "plus",
> "minus"..?
>
> Like in C++:
> > template<typename T>
> > T operator+(T first, T second)
> >
> >{
> >
> >    return static_cast<T>(first + second);
> >
> >}

D only allows overloaded operators to be declared on types, so you can't
overload any operators for any built-in types (or any types that you don't
control the declaration of for that matter). You could create a wrapper
function and use that instead of +. You could even make it use string mixins
like opBinary does if you wanted to - e.g. something like

short doOp(string op)(short lhs, short rhs)
    if(op == "+" || op == "-" || op == "*" || op == "/" || op == "%")
{
    mixin("return cast(short)(lhs " ~ op ~ " rhs);");
}

val1 = val1.doOp!"+"(val2);

but you're not going to be able to get something like

val1 = val1 + val2;

to work with just short.

Alternatively, you could create a wrapper type and use that instead of using
short directly. IIRC, the last time that someone was complaining in the main
newsgroup about all of the required casts, someone posted a link to
something that did that. If the casts are too annoying for you, that would
probably be the best solution.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list