On 07/22/2018 03:51 PM, aliak wrote:
> Hi,
>
> In the code below:
>
> struct W(T) {
>      T val;
>      this(T val) inout {
>          this.val = val;
>      }
> }
>
> class C {}
>
> void main() {
>     W!C a = new C;
>     immutable W!C b = new C;
> }
>
> W!C a = new C results in: "Error: cannot implicitly convert expression
> val of type C to inout(C)."
>
> If I remove the inout on the constructor then the error is on the other
> line and is: "Error: mutable method W!(C).W.this is not callable using a
> immutable object"
>
> If the class is changed to a struct through,  then the constructor with
> inout works on both lines in main above.
>
> So I guess this has something to do with reference types (As the same
> behaviour is exhibited if T == int*) What's the recommended way to
> handle this?
>
> Cheers,
> - Ali

Without much confidence on my side, first, I think you need to make the constructor parameter inout(T) as well. Otherwise, you may be making a const(W!T) initialized with a non-const T.

After that, I like the "type constructor" syntax in main_alt() below (which works) but a better approach is to use a convenience function like wrap() below:

struct W(T) {
    T val;
    this(inout(T) val) inout {
        this.val = val;
    }
}

class C {}

void main_alt() {
    auto a = W!C(new C);
    auto b = immutable W!(immutable C)(new C);
}

auto wrap(T)(inout T t) {
    return inout(W!T)(t);
}

void main() {
    auto a = wrap(new C);
    auto b = wrap(new immutable(C));
}

Ali
"taklitlerinden sakınınız" :o)

Reply via email to