Recent

Author Topic: Creating a generic function  (Read 2751 times)

PascalDragon

  • Hero Member
  • *****
  • Posts: 716
  • Compiler Developer
Re: Creating a generic function
« Reply #15 on: June 25, 2019, 09:48:33 am »
Is there any way to have generic function here that will print any type of printable item array sent to it?
Is it possible to have simple generic functions?
In FPC 3.0 only via generic types:
Code: Pascal  [Select]
  1. {$APPTYPE CONSOLE}
  2. {$MODE DELPHI}
  3. type
  4.   TPrintArray<T> = class(TObject)
  5.   public
  6.     class procedure DoPrint(const A: array of T); static;
  7.   end;
  8.  
  9. class procedure TPrintArray<T>.DoPrint(const A: array of T);
  10. var
  11.   Item: T;
  12. begin
  13.   for Item in A do
  14.     Write(Item, ',');
  15.   Writeln;
  16. end;
  17.  
  18. begin
  19.   TPrintArray<Integer>.DoPrint([1, 2, 3]);
  20.   TPrintArray<string>.DoPrint(['11', '22', '33']);
  21.   Readln;
  22. end.
You don't need to declare a class, you can also use a record instead (requires {$modeswitch advancedrecords} in mode ObjFPC).

rnfpc

  • Jr. Member
  • **
  • Posts: 91
Re: Creating a generic function
« Reply #16 on: June 25, 2019, 02:32:10 pm »
It will be great if you can post here some code using records in this manner.

PascalDragon

  • Hero Member
  • *****
  • Posts: 716
  • Compiler Developer
Re: Creating a generic function
« Reply #17 on: June 26, 2019, 03:22:43 pm »
Mode Delphi:
Code: Pascal  [Select]
  1. {$APPTYPE CONSOLE}
  2. {$MODE DELPHI}
  3. type
  4.   TPrintArray<T> = record
  5.   public
  6.     class procedure DoPrint(const A: array of T); static;
  7.   end;
  8.      
  9. class procedure TPrintArray<T>.DoPrint(const A: array of T);
  10. var
  11.   Item: T;
  12. begin
  13.   for Item in A do
  14.     Write(Item, ',');
  15.   Writeln;
  16. end;
  17.      
  18. begin
  19.   TPrintArray<Integer>.DoPrint([1, 2, 3]);
  20.   TPrintArray<string>.DoPrint(['11', '22', '33']);
  21.   Readln;
  22. end.

Mode ObjFPC:
Code: Pascal  [Select]
  1. {$APPTYPE CONSOLE}
  2. {$MODE OBJFPC}
  3. {$MODESWITCH ADVANCEDRECORDS}
  4. type
  5.   generic TPrintArray<T> = record
  6.   public
  7.     class procedure DoPrint(const A: array of T); static;
  8.   end;
  9.  
  10. class procedure TPrintArray.DoPrint(const A: array of T);
  11. var
  12.   Item: T;
  13. begin
  14.   for Item in A do
  15.     Write(Item, ',');
  16.   Writeln;
  17. end;
  18.      
  19. type
  20.   { Note: inline specialization in mode ObjFPC requires FPC 3.2.0 or newer,
  21.      but then you can also use generic functions... }
  22.   TPrintArrayInteger = specialize TPrintArray<Integer>;
  23.   TPrintArrayString = specialize TPrintArray<String>;
  24.  
  25. begin
  26.   TPrintArrayInteger.DoPrint([1, 2, 3]);
  27.   TPrintArrayString.DoPrint(['11', '22', '33']);
  28.   Readln;
  29. end.

Both tested with FPC 3.0.4.