Lazarus

Programming => General => Topic started by: bpranoto on March 26, 2023, 12:21:28 pm

Title: Generic: array of T
Post by: bpranoto on March 26, 2023, 12:21:28 pm
Why is it not compiled?

Code: Pascal  [Select][+][-]
  1. program Project1;
  2. uses sysutils;
  3.  
  4. var
  5.   ATanggal:array of TDate;
  6.  
  7. generic procedure ArrayAdd<T>( var A:array of T ; Item:T);
  8. var
  9.   i:Integer;
  10. begin
  11.   i := Length(A);
  12.   SetLength(A,i+1);  // <=== Error: type mismatch
  13.   A[i]:=item;
  14. end;
  15.  
  16. begin
  17.   SetLength(ATanggal,0);
  18.   specialize ArrayAdd<TDate>( ATanggal, Date);
  19. end.
  20.  
Title: Re: Generic: array of T
Post by: Thaddy on March 26, 2023, 12:33:48 pm
Because, again, many people do that, you are mixing up  open array parameters with dynamic arrays.
The correct way is something like this:
Code: Pascal  [Select][+][-]
  1. {$mode objfpc}{$H+}
  2. uses sysutils;
  3.  
  4. var
  5.   ATanggal:array of TDate;
  6.  
  7. generic procedure ArrayAdd<T>( var A:specialize TArray<T> ; Item:T); // take a good look!!
  8. var
  9.   i:Integer;
  10. begin
  11.   i := Length(A);
  12.   SetLength(A,i+1);  // <=== No Error
  13.   A[i]:=item;
  14. end;
  15.  
  16. begin
  17.   SetLength(ATanggal,0);
  18.   specialize ArrayAdd<TDate>( ATanggal, Date);
  19. end.

There's more wrong, but the above is close to your code and works. At least with trunk. Can't test other versions today.
Title: Re: Generic: array of T
Post by: bpranoto on March 26, 2023, 12:39:20 pm
Thank you for the enlightment.
Title: Re: Generic: array of T
Post by: bpranoto on March 26, 2023, 03:05:59 pm
There's more wrong, but the above is close to your code and works. At least with trunk. Can't test other versions today.

it works with fpc 3.2.2
TinyPortal © 2005-2018