unit Genericpair; {$mode objfpc}{$H+} interface uses Classes,SysUtils,Dialogs; type generic TGenericpair<_T1,_T2> = class private first : _T1; second : _T2; public constructor Create(T1_:_T1 ;T2_:_T2); overload; destructor Destroy; override; 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; ... end.
First of all we define a new type, a generic one: in particular this is a class called TGenericpair, who accepts two input parameters: _T1, _T2.
[The underscore is for sake of convention, just to remember they're parameters]
Specialization is direct just to these two - whose nature is unknown - rather than to the type; in facts we know this last is a class, as said.
Obviously procedures and functions are required to manipulate the value passed through the generics: here simply we set and get their values.
By reading the code you could think that it's just a kind of joke: apparently you're right, but the beauty is when you begin to utilize the template.
In the main file of the present project, we specialize four generic pairs. Look at the following code:
type TPairStrInt = specialize TGenericpair<string,integer>; TPairStrStr = specialize TGenericpair<string,string>; TPairStrDouble = specialize TGenericpair<string,double>; TPairStrEmployee = specialize TGenericpair<string,TEmployee>;
[As always we're dealing with the Employee class]
See the news: specialization not only gives a specific type to both of the parameters, but it assigns a name to the generic type too (here, a class)!
That's important and right; otherwise how could you call a class with the same name - TGenericpairs - and different parameters?
We saw this by talking about the virtual and abstract modifiers, which force the coder to override in inheriting classes; but we're facing another situation, even if a form of polymorphism can be recognized.
That's nothing more to explain about the basics of template or generics: we're not saying they're easy and simple.
As always our goal is to make concepts usable in few moments, to give a base which to start from.
In the main file's code you'll find four declarations, one for every specialized class, of variables where to store the pairs with Create constructor method.
After the GetFirst and GetSecond functions are used to get the values.
Lastly the destructors are called.
And now the whole code of units, except the Employee that at this point you should know.