On Sunday, 22 October 2017 at 10:57:24 UTC, NX wrote:
On Sunday, 22 October 2017 at 02:25:44 UTC, codephantom wrote:
On Saturday, 21 October 2017 at 20:17:12 UTC, NX wrote:
Interestingly enough, I realized that atan() returns double (in this case) but wait, it's assigned to a float variable! Compiler didn't even emit warnings, let alone errors.


There a few lessons here.

(1) D is not Java ;-)

D is not C/C++ either. I fail to see how does it help to be C++ compliant. It's absolutely trivial to tell the compiler that conversion is on purpose by explicitly casting and it immensely helps to reduce bugs (since we are humans after all).

(2) Know what types are being returned from your calls, before you call them. (3) Know what the language spec says about conversions (and their order):
    - https://dlang.org/spec/type.html
(4) If unsure, test it:
- https://dlang.org/phobos/std_traits.html#isImplicitlyConvertible

Only then should you start coding ;-)

It never crossed my mind that D would allow such type conversion since I don't recall any language that markets itself as _modern_ allows it.

oh...and...

(5) Don't waste time arguing with the spec ;-)
(6) Don't expect the compiler to not comply with the spec

I just think spec should be reviewed at this point.

Fortunately D provides enough to simplify self-discipline:

---
import std.traits;

struct FP(T)
if (isFloatingPoint!T)
{
    T _value;
    alias _value this;

    void antiCoercion(V)()
    {
static assert(V.sizeof <= T.sizeof, "C++ float coercion is not allowed");
    }

    this(V)(V v) {antiCoercion!V; _value = v;}
    void opAssign(V)(V v) {antiCoercion!V; _value = v;}
}

void main()
{
    import std.math;
    FP!single PiOver2 = (atan(1.0) * 4) / 2;
}
---

Reply via email to