Arithmetic operations with generic types in Delphi

前端 未结 3 681
小鲜肉
小鲜肉 2021-01-12 16:54

I\'m new in Delphi. For a project required by my company, I need to translate some code from our existing C++ classes to Delphi. Some of these classes are templates, such as

3条回答
  •  悲&欢浪女
    2021-01-12 17:39

    Pointing this out for anyone else looking for an Object Pascal solution to this general issue:

    Note that Free Pascal quite simply does support exactly what they're trying to do here (even in "Delphi-syntax compatibility" mode.)

    As someone who had only used Free Pascal for a long time, I was honestly very surprised that Delphi doesn't allow this at all, once I realized that was the case. It's a significant limitation IMO.

    Valid Free Pascal code:

    program Example;
    
    // Using Delphi-mode here allows us to declare and use
    // generics with the same syntax as Delphi, as opposed to
    // needing the "generic" and "specialize" keywords that
    // FPC normally requires.
    
    {$mode Delphi}
    
    // To allow +=, another nice FPC feature...
    
    {$COperators On}
    
    type
      TGPoint = record
        X, Y: T;
        // static class function instead of constructor here so we can inline it
        class function Create(constref AX, AY: T): TGPoint; static; inline;
        // define our operator overload
        class operator Add(constref Left, Right: TGPoint): TGPoint; inline;
      end;
    
      class function TGPoint.Create(constref AX, AY: T): TGPoint;
      begin
        with Result do begin
          X := AX;
          Y := AY;
        end;
      end;
    
      class operator TGPoint.Add(constref Left, Right: TGPoint): TGPoint;
      begin
        with Result do begin
          X := Left.X + Right.X;
          Y := Left.Y + Right.Y;
        end;
      end;
    
    var SP: TGPoint;
    
    begin
      SP := TGPoint.Create('Hello, ', 'Hello, ');
      SP += TGPoint.Create('world!', 'world!');
      with SP do begin
        WriteLn(X);
        WriteLn(Y);
      end;
    end.
    

    The program of course prints:

    Hello, world!
    Hello, world!
    

提交回复
热议问题