How do I test a generic type variable for equality with Default(T) in Delphi?

后端 未结 2 1575
无人及你
无人及你 2021-01-05 17:30

I\'m trying to write a generic cached property accessor like the following but am getting a compiler error when trying to check whether the storage variable already contains

相关标签:
2条回答
  • 2021-01-05 18:04

    The problem is not the Default function, but the equality operator =.

    You could constrain T to IEquatable and use the Equals method like this:

    TMyClass = class
      function GetProp<T : IEquatable<T>>(var ADataValue: T; const ARetriever: 
    end;
    ...
    function TMyClass.GetProp<T>(var ADataValue: T; const ARetriever: TFunc<T>): T;
    begin  
    if ADataValue.Equals (Default(T)) then
      ADataValue := ARetriever();  
    Result := ADataValue;
    end;   
    
    0 讨论(0)
  • 2021-01-05 18:24

    After a hint in the comments from Binis and digging around a little in Generics.Collections I came up with the following which appears to work just as I wanted it:

    function TMyClass.GetProp<T>(var ADataValue: T; const ARetriever: TFunc<T>): T;
    var
      lComparer: IEqualityComparer<T>;
    begin
      lComparer := TEqualityComparer<T>.Default;
      if lComparer.Equals(ADataValue, Default(T)) then
        ADataValue := ARetriever();
      Result := ADataValue;
    end;
    
    0 讨论(0)
提交回复
热议问题