On Sunday, 14 January 2018 at 16:23:18 UTC, kdevel wrote:
Why does this compile while both of the commented lines give a compile error.

The code boils down to this:

----
struct decimal32
{
    this(int x) {}
}

immutable decimal32 c = 3; /* works */

void main ()
{
   immutable decimal32 i = 1; /* error */
}
----

I think this is CTFE being unexpectedly smart.

If you add the `pure` attribute to the constructor, then the `i` line works as well. That's because a strongly pure constructor is guaranteed to return a unique object, and a unique object can be converted implicitly to other mutability levels.

The `pure` attribute is needed for `i`, because here the compiler only looks at the function attributes to determine purity. No `pure` attribute -> function is regarded as impure.

But for `c`, the constructor goes through CTFE, and CTFE doesn't care all that much about the `pure` attribute. Instead, CTFE just tries to evaluate the function and aborts when it encounters an action that would be impure.

Reply via email to