How to get an inout constructor working with a template wrapper

aliak something at something.com
Mon Jul 23 12:02:58 UTC 2018


On Sunday, 22 July 2018 at 23:11:09 UTC, Ali Çehreli wrote:
> 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)

Thank you Ali! That helped :) I've gotten most of it sorted out 
now, and the factory wrap is definitely the way to go, it also 
turned out that inout(T) and inout T (so inout without parens) 
was surprisingly different (maybe it's a bug? - to test you can 
remove the parens around U on line 3 in this sample: 
https://run.dlang.io/is/gd5oxW

Also over there, line 24:

auto si = wrap!(immutable int)(3);

seems to be giving problems. Any ideas there? Error is:

onlineapp.d(8): Error: inout on return means inout must be on a 
parameter as well for pure nothrow @nogc @safe 
inout(W!(immutable(int)))(immutable(int) t)
onlineapp.d(23): Error: template instance 
`onlineapp.wrap!(immutable(int))` error instantiating

To make it compile successfully you can either:

1) Chance immutable to const, then it works for some reason.
2) Change the line to: "auto si = wrap(cast(immutable int)3);" - 
i.e. do not explicitly provide type information.

Cheers,
- Ali



More information about the Digitalmars-d-learn mailing list