Recent

Author Topic: Creating generic object in generic method  (Read 1143 times)

Milsa

  • Sr. Member
  • ****
  • Posts: 309
Creating generic object in generic method
« on: September 22, 2019, 03:56:57 pm »
What is wrong in this?
Code: Pascal  [Select][+][-]
  1.  
  2. ...
  3. type
  4.   generic TAssoc<T> = class
  5.   private
  6.     FName: String;
  7.     FValue: T;
  8.     FList: specialize TAssoc<T>;
  9. ...
  10. function TAssoc.GetItem(AName: String): specialize TAssoc<T>;
  11. var
  12.   TList: specialize TAssoc<T>;
  13. ...
  14.   Result.FList := specialize TAssoc<T>.Create(AName); //<-- error message
  15. ...
  16.  
Message is:
Quote
assocarr.pas(52,19) Error: Identifier not found "specialize"
Result is created object and FList is subobject created in this time.
« Last Edit: September 22, 2019, 04:02:48 pm by Milsa »
I work with Lazarus 2.2.2, FPC 3.2.2, date 2022-05-15
This information is actual to: 28st Dec 2022

avk

  • Hero Member
  • *****
  • Posts: 752
Re: Creating generic object in generic method
« Reply #1 on: September 22, 2019, 06:03:54 pm »
I don’t know the version of your compiler, but this code compiles by FPC 3.3.1:
Code: Pascal  [Select][+][-]
  1. ...
  2. type
  3.   generic TAssoc<T> = class
  4.   private
  5.   type
  6.     TAssocSpec = specialize TAssoc<T>;
  7.  
  8.   var
  9.     FName: String;
  10.     FValue: T;
  11.     FList: specialize TAssoc<T>;
  12.   ...
  13. function TAssoc.GetItem(AName: String): specialize TAssoc<T>;
  14. var
  15.   TList: TAssoc;
  16. begin
  17.   ...
  18.   Result.FList := TAssocSpec.Create(AName);
  19.   ...
  20. end;  
  21.  
Perhaps this will not help you much, because your code compiles by FPC 3.3.1 as well.
« Last Edit: September 22, 2019, 06:21:59 pm by avk »

ASerge

  • Hero Member
  • *****
  • Posts: 2212
Re: Creating generic object in generic method
« Reply #2 on: September 22, 2019, 08:19:19 pm »
Why complicate things?
Code: Pascal  [Select][+][-]
  1. ...
  2.     FList: TAssoc;
  3. ...
  4. function TAssoc.GetItem(const AName: string): TAssoc;
  5. ...
  6.   Result := TAssoc.Create(AName);

Milsa

  • Sr. Member
  • ****
  • Posts: 309
Re: Creating generic object in generic method
« Reply #3 on: September 22, 2019, 08:40:55 pm »
All two solutions work. Thank you.
I work with Lazarus 2.2.2, FPC 3.2.2, date 2022-05-15
This information is actual to: 28st Dec 2022

 

TinyPortal © 2005-2018