Troubles creating templated inout objects

Timoses timosesu at gmail.com
Thu Jul 12 08:22:42 UTC 2018


On Wednesday, 11 July 2018 at 12:55:35 UTC, Timoses wrote:
> On Tuesday, 10 July 2018 at 18:01:59 UTC, Steven Schveighoffer 
> wrote:
>> You are overthinking :) inout typically is much easier than 
>> you expect, until you need to create temporary structs or 
>> types with inout members, then it becomes problematic.
>>
>> https://run.dlang.io/is/kosYuC
>>
>> I had to put in a static if, because your function doesn't 
>> work once you get down to the array type. See the // fixme 
>> comment.
>
> Ok, well that helped a tiny bit for the example.
>
> I'm trying to reproduce the errors from my project. It's 
> starting to get out of control : D. inout is on a rampage!
>
> https://run.dlang.io/is/5TN7XX
>
> I guess it's the same as for immutable initialization of 
> arrays. I can't seem to find a proper response to this one..
>
> [...]
> 	class TestA(T : T[])
> 	{
> 		Test!T[] arr;
>
>                 // ERROR: Can't initialize inout variable in a 
> for loop...
> 		this(inout(T[]) arr) inout
> 		{
> 			// 1: Nope
> 			foreach (mem; arr)
> 			    this.arr ~= test(mem);
>
> 			// 2: Nope
> 			//Test!T[] a;
> 			//foreach (mem; arr)
> 			//   a ~= test(mem);
>
> 			import std.algorithm : map;
> 			// 3: Nope
> 			// this.arr = arr.map!((e) => test(e)).array;
> 		}
> 	}
>
> [...]


I guess the problem here is focused around the problem that the 
incoming type in the constructor is inout and that the 
constructed object itself is inout.

I can't seem to find another way, I'm just blatantly casting 
now...

class TestA(T : T[])
{
     Test!T[] arr;
     this(inout(T[]) arr) inout
     {
         import std.algorithm : map;
         import std.range: array;
         // should be okay to cast to const, won't change anything
         auto ts = cast(const T[])arr;
         // should be okay as well, as `test(t)` creates a new 
object
         this.arr = cast(inout(Test!T[]))(ts.map!(t => 
test(t)).array);
     }
}

I also found `assumeUnique` in std.exception, or 
std.experimental.allocator.makeArray. I'm not to sure how they 
might be able to circumvent the casting though, since I need an 
inout array of the objects...

Am I missing something or is `inout` simply not that well 
"implemented" yet?




More information about the Digitalmars-d-learn mailing list