How to use generics/fr
English · Français
Un exemple de comment utiliser des génériques pour écrire une
function gmax()qui prend la maximum de deux variables non encore typées. Remarquez que les fonctions sont nommées dans leur espace (namespaced) par leur nom de classe. Un inconvénient peut être que les génériques ne peuvent surchargées. Notez encore que l'opérateur devra être défini pour le type précisé lors de la spécialisation.
program UseGenerics;
{$mode objfpc}{$H+}
type
generic TFakeClass<_GT> = class
class function gmax(a,b: _GT):_GT;
end;
TFakeClassInt = specialize TFakeClass<integer>;
TFakeClassDouble = specialize TFakeClass<double>;
class function TFakeClass.gmax(a,b: _GT):_GT;
begin
if a > b then
result := a
else
result := b;
end;
begin
// show max of two integers
writeln( 'Integer GMax:', TFakeClassInt.gmax( 23, 56 ) );
// show max of two doubles
writeln( 'Double GMax:', TFakeClassDouble.gmax( 23.89, 56.5) );
readln();
end.From the Free Pascal wiki, page "How to use generics/fr", as it stood on 2019-07-01 after a change by Djzepi, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.