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);
}

Reply via email to