[fpc-pascal] [OT] Generics and Type Constraints sample

silvioprog silvioprog at gmail.com
Thu Oct 30 20:48:19 CET 2014


Hello,

I tried this example (Lazarus 1.3 r46702 FPC 2.7.1 x86_64-linux-gtk 2; FPC
from trunk too):

http://blogs.teamb.com/craigstuntz/2008/08/29/37832

and got the error:

Compile Project, Target: project1: Exit code 256, Errors: 3
unit1.pas(27,22) Error: Identifier not found "T"
unit1.pas(27,23) Error: Type identifier expected
unit1.pas(27,24) Error: Class or interface type expected, but got
"<erroneous type>"

The code:

unit Unit1;

//{$mode objfpc}{$H+}
{$mode delphi}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs;

type
  TAdder<T> = class
  public
    function AddEm(A, B: T): T; virtual; abstract;
  end;

  TIntAdder = class(TAdder<integer>)
  public
    function AddEm(A, B: integer): integer; override;
  end;

  TStringAdder = class(TAdder<string>)
  public
    function AddEm(A, B: string): string; override;
  end;

  TMath<T; A: TAdder<T>, constructor> = class
  public
     function AddTwoDigits(Left, Right: T): T;
  end;

  { TForm1 }

  TForm1 = class(TForm)
    procedure Button1Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
var
  AddInt: TMath<integer, TIntAdder>;
  AddString: TMath<string, TStringAdder>;
begin
  AddInt := TMath<integer, TIntAdder>.Create;
  try
    ShowMessage(IntToStr(AddInt.AddTwoDigits(2, 2)));
  finally
    AddInt.Free;
  end;
  AddString := TMath<string, TStringAdder>.Create;
  try
    ShowMessage(AddString.AddTwoDigits('2', '2'));
  finally
    AddString.Free;
  end;
end;

{ TIntAdder }

function TIntAdder.AddEm(A, B: integer): integer;
begin
  Result := A + B;
end;

{ TStringAdder }

function TStringAdder.AddEm(A, B: string): string;
begin
  Result := IntToStr(StrToInt(A) + StrToInt(B));
end;

{ TMath<T, A> }

function TMath<T, A>.AddTwoDigits(Left, Right: T): T;
var
  Add: A;
begin
  Add := A.Create;
  try
    Result := Add.AddEm(Left, Right);
  finally
    Add.Free;
  end;
end;

end.

--
Silvio Clécio
My public projects - github.com/silvioprog
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20141030/bf5598a4/attachment.html>


More information about the fpc-pascal mailing list