Skip to content

Generics and templates

And here the Genericpair unit's code:

unit Genericpair;

{$mode objfpc}{$H+}

interface

uses
  Classes,SysUtils,Dialogs;

type
  generic TGenericpair<_T1,_T2> = class 

  private //PRIVATE ZONE
    first : _T1;
    second : _T2;

  protected //PROTECTED ZONE

  public   //PUBLIC (Anyone can see this zone)
    constructor Create(T1_:_T1 ;T2_:_T2); overload; //Public Class Method
    //The Overload allows you to have different versions of the same named
    //function/procedure with different arguments
    //OVERLOAD : SAME NAME OF FUNCTION WITH DIFFERENT ARGUMENTS IN THE SAME CLASS

    //Destructor (can be only ONE)
    Destructor Destroy; override;                          //Public Class Method
    //The Override must be specified since we are overriding the virtual TObject destroy method.
    //At the end of a destructor, you should call Inherited to invoke the parent destructor.
    //OVERRIDE : SAME NAME OF FUNCTION WITH SAME ARGUMENTS IN DIFFERENT CLASSES

    function GetFirst():_T1;                              //Public Object Method
    procedure SetFirst(T1_:_T1);                          //Public Object Method

    function GetSecond():_T2;                              //Public Object Method
    procedure SetSecond(T2_:_T2);                          //Public Object Method

  end;

implementation

//implementation of the methods here !!!

//Class Method
constructor TGenericpair.Create(T1_:_T1 ;T2_:_T2); overload;
begin
  self.First:=T1_;
  self.Second:=T2_;
end;

//Class Method
Destructor TGenericpair.Destroy; //override; //not needed here !!!
begin
  showmessage('Pair destroyed');

  inherited; // Always call the parent destructor after running your own code
end;

//Object Method
function TGenericpair.GetFirst():_T1;
begin
  result := self.First;
end;

//Object Method
procedure TGenericpair.SetFirst(T1_:_T1);
begin
 self.First := T1_;
end;

//Object Method
function TGenericpair.GetSecond():_T2;
begin
  result := self.Second;
end;

//Object Method
procedure TGenericpair.SetSecond(T2_:_T2);
begin
 self.Second := T2_;
end;

end.

That's all for now.
Hope we made this argument a bit clearer than it can appear the first time.

The main advice is the same: try it yourself, modify the code to get a result you have in mind, check the real result.

And if you get errors don't be sad: they're a big chance to improve your knowledge.

Thanks.