Recent

Author Topic: Generic sub types  (Read 623 times)

Okoba

  • Hero Member
  • *****
  • Posts: 533
Generic sub types
« on: January 01, 2023, 04:17:32 pm »
Hello,

I am trying to use a type from another type.
Test is working but Test2 raises an error. Why?

Code: Pascal  [Select][+][-]
  1. program Project1;
  2.  
  3.   {$mode delphi}
  4.  
  5. type
  6.   T1 = object
  7.   type
  8.     T2 = Integer;
  9.   end;
  10.  
  11.   T3<T> = object
  12.     procedure Test;
  13.     procedure Test2;
  14.   end;
  15.  
  16.   T4 = T3<T1>;
  17.  
  18.   procedure T3<T>.Test;
  19.   begin
  20.     WriteLn(SizeOf(T.T2));
  21.   end;
  22.  
  23.   procedure T3<T>.Test2;
  24.   var
  25.     A: T.T2; // Error: Error in type definition
  26.   begin
  27.  
  28.   end;
  29.  
  30. var
  31.   V: T4;
  32. begin
  33.   V.Test;
  34.   ReadLn;
  35. end.

ASerge

  • Hero Member
  • *****
  • Posts: 2246
Re: Generic sub types
« Reply #1 on: January 01, 2023, 09:20:26 pm »
I am trying to use a type from another type.
Test is working but Test2 raises an error. Why?
In my opinion, even when compiling the Test procedure, an error should occur. Let 's rewrite it in a different way:
Code: Pascal  [Select][+][-]
  1. {$MODE DELPHI}
  2. {$APPTYPE CONSOLE}
  3.  
  4. type
  5.   TObj<T> = object
  6.     procedure Test;
  7.   end;
  8.  
  9. procedure TObj<T>.Test;
  10. begin
  11.   WriteLn(SizeOf(T.T2)); // At this point T.T2 is unknown ???
  12. end;
  13.  
  14. type
  15.   TClass = class
  16.     type T2 = Integer;
  17.   end;
  18.  
  19. var
  20.   V: TObj<TClass>;
  21. begin
  22.   V.Test;
  23.   ReadLn;
  24. end.

But if we explicitly restrict the template type, then there will be no problems:
Code: Pascal  [Select][+][-]
  1. {$MODE DELPHI}
  2. {$APPTYPE CONSOLE}
  3.  
  4. type
  5.   TClass = class
  6.     type T2 = Integer;
  7.   end;
  8.  
  9.   TObj<T: TClass> = object
  10.     procedure Test;
  11.   end;
  12.  
  13. procedure TObj<T>.Test;
  14. var
  15.   A: T.T2;
  16. begin
  17.   WriteLn(SizeOf(A));
  18. end;
  19.  
  20. var
  21.   V: TObj<TClass>;
  22. begin
  23.   V.Test;
  24.   ReadLn;
  25. end.

PascalDragon

  • Hero Member
  • *****
  • Posts: 5486
  • Compiler Developer
Re: Generic sub types
« Reply #2 on: January 02, 2023, 11:10:01 pm »
Test is working but Test2 raises an error. Why?

Please report a bug.

I am trying to use a type from another type.
Test is working but Test2 raises an error. Why?
In my opinion, even when compiling the Test procedure, an error should occur.

FPC's generics are more like C++'s than Delphi's or C#'s so such things do work. Using a class constraint will simply increase type safety (and thus that is indeed the recommended approach anyway).

 

TinyPortal © 2005-2018