tw18688.pp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. unit tw18688;
  2. {$mode delphi}{$H+}
  3. interface
  4. uses
  5. Classes, SysUtils;
  6. type
  7. IValueHolder<T> = interface
  8. function GetT:T;
  9. procedure SetT(NewValue:T);
  10. end;
  11. TValueHolder <T> = class (TInterfacedObject, IValueHolder<T>)
  12. private
  13. FValue: T;
  14. public
  15. constructor Create;
  16. destructor Destroy; override;
  17. function GetT:T;
  18. procedure SetT(NewValue:T);
  19. end;
  20. RValueHolder<T> = record
  21. private
  22. type
  23. _IValueHolder = IValueHolder<T>;
  24. _TValueHolder = TValueHolder<T>;
  25. var
  26. Ptr: _IValueHolder;
  27. function GetImpl: _IValueHolder;
  28. public
  29. class operator Implicit (a:RValueHolder<T>):T; inline;
  30. class operator Implicit (a:T):RValueHolder<T>; inline;
  31. function GetValue:T; inline;
  32. property V:T read GetValue;
  33. end;
  34. //TObjectValue = TValueHolder<TObject> ; // works if not commented
  35. TObjectValue2 = RValueHolder<TObject> ;
  36. implementation
  37. constructor TValueHolder <T>.Create;
  38. begin
  39. FValue := nil
  40. end;
  41. destructor TValueHolder <T>.Destroy;
  42. begin
  43. FreeAndNil(FValue);
  44. inherited;
  45. end;
  46. function TValueHolder <T>.GetT:T;
  47. begin
  48. Result := FValue;
  49. end;
  50. procedure TValueHolder <T>.SetT(NewValue:T);
  51. begin
  52. if FValue <> NewValue then
  53. begin
  54. FreeAndNil(FValue);
  55. FValue := NewValue;
  56. end;
  57. end;
  58. function RValueHolder<T>.GetImpl: _IValueHolder;
  59. begin
  60. if Pointer(Ptr) = nil then
  61. begin
  62. Ptr := _TValueHolder.Create;
  63. end;
  64. Result := Ptr;
  65. end;
  66. class operator RValueHolder<T>.Implicit (a:RValueHolder<T>):T;
  67. begin
  68. Result:=a.V;
  69. end;
  70. class operator RValueHolder<T>.Implicit (a:T):RValueHolder<T>;
  71. begin
  72. Result.GetImpl.SetT(a);
  73. end;
  74. function RValueHolder<T>.GetValue:T;
  75. begin
  76. Result := GetImpl.GetT;
  77. end;
  78. end.