code_junkie

How do I handle Delphi Simple types when using generics?

Nov 12th, 2011
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. TTest<T> = class
  2. private
  3. f : T;
  4. public
  5. function ToString : string;
  6. end;
  7.  
  8. TTest<T>.ToString;
  9. begin
  10. Result := f.ToString;
  11. end;
  12.  
  13. TTest<T: TObject>.ToString;
  14. begin
  15. Result := T.ToString;
  16. end;
  17.  
  18. type
  19. TToString<T> = reference to function(const AValue: T): string;
  20. TGenContainer<T> = class
  21. private
  22. FValue: T;
  23. FToString : TToString<T>;
  24. public
  25. constructor Create(const AToString: TToString<T>);
  26.  
  27. function ToString: string;
  28.  
  29. property Value: T read FValue write FValue;
  30. end;
  31.  
  32. constructor TGenContainer<T>.Create(const AToString: TToString<T>);
  33. begin
  34. FToString := AToString;
  35. end;
  36.  
  37. function TGenContainer<T>.ToString: string;
  38. begin
  39. Result := FToString(FValue);
  40. end;
  41.  
  42.  
  43.  
  44. procedure TForm2.Button1Click(Sender: TObject);
  45. var
  46. gen : TGenContainer<Integer>;
  47. begin
  48. gen := TGenContainer<Integer>.Create(
  49. function(const AValue: Integer): string
  50. begin
  51. Result := IntToStr(AValue);
  52. end);
  53. try
  54. gen.Value := 17;
  55. Memo1.Lines.Add(gen.ToString);
  56. finally
  57. gen.Free;
  58. end;
  59. end;
Add Comment
Please, Sign In to add comment