www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Dynamic array of Cycle buffers of size 2 which use a struct?

reply =?iso-8859-1?Q?Robert_M._M=FCnch?= <robert.muench saphirion.com> writes:
I don't get how I can create a dynamic array of Cycle buffers of size 2 
which use a struct.

  struct ms {
    int a;
    int b;
  }
  ms[2] msBuffer;
  alias circularStructBuffersT = typeof(cycle(msBuffer));
  circularStructBuffersT[int] circularStructBuffers;

  int i = 2;
  auto x = circularStructBuffers.require(i, (){
    ms[2] t;
    return cycle(t,2);
  });

This give an error:

Error: template object.require cannot deduce function from argument 
types !()(Cycle!(ms[2])[int], int, Cycle!(ms[2]) function() pure 
nothrow  nogc  system), candidates are:
/Library/D/dmd/src/druntime/import/object.d(3225):        require(K, 
V)(ref V[K] aa, K key, lazy V value = V.init)

Not sure if the `m[2] t` survives the scope exit in form of a closure 
(?) or if cycle takes a reference to it...

-- 
Robert M. Münch
http://www.saphirion.com
smarter | better | faster
Feb 22 2020
parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 2/22/20 2:29 PM, Robert M. M=C3=BCnch wrote:
 I don't get how I can create a dynamic array of Cycle buffers of size 2=
=20
 which use a struct.
=20
  =C2=A0struct ms {
  =C2=A0=C2=A0 int a;
  =C2=A0=C2=A0 int b;
  =C2=A0}
  =C2=A0ms[2] msBuffer;
  =C2=A0alias circularStructBuffersT =3D typeof(cycle(msBuffer));
  =C2=A0circularStructBuffersT[int] circularStructBuffers;
=20
  =C2=A0int i =3D 2;
  =C2=A0auto x =3D circularStructBuffers.require(i, (){
  =C2=A0=C2=A0 ms[2] t;
  =C2=A0=C2=A0 return cycle(t,2);
  =C2=A0});
It looks like require() requires :) a value, which it evaluates only if=20 necessary: https://dlang.org/spec/hash-map.html#inserting_if_not_present In your case, you're passing a callable. All you need to do is to=20 actually call that callable with empty parenthesis: auto x =3D circularStructBuffers.require(i, { // ... }()); // <-- HERE Because the parameter is lazy, it will still be called only when needed. Ali
Feb 22 2020