How to use generics/fr: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: How to use generics/fr
| Old | New | Line | |
|---|---|---|---|
| 1 | + | Un exemple de comment utiliser des génériques pour écrire une | |
| 2 | + | ||
| 3 | + | ``` pascal | |
| 4 | + | function gmax() | |
| 5 | + | ``` | |
| 6 | + | ||
| 7 | + | 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. | |
| 8 | + | ||
| 9 | + | ``` pascal | |
| 10 | + | program UseGenerics; | |
| 11 | + | ||
| 12 | + | {$mode objfpc}{$H+} | |
| 13 | + | ||
| 14 | + | type | |
| 15 | + | generic TFakeClass<_GT> = class | |
| 16 | + | class function gmax(a,b: _GT):_GT; | |
| 17 | + | end; | |
| 18 | + | ||
| 19 | + | TFakeClassInt = specialize TFakeClass<integer>; | |
| 20 | + | TFakeClassDouble = specialize TFakeClass<double>; | |
| 21 | + | ||
| 22 | + | class function TFakeClass.gmax(a,b: _GT):_GT; | |
| 23 | + | begin | |
| 24 | + | if a > b then | |
| 25 | + | result := a | |
| 26 | + | else | |
| 27 | + | result := b; | |
| 28 | + | end; | |
| 29 | + | ||
| 30 | + | begin | |
| 31 | + | // show max of two integers | |
| 32 | + | writeln( 'Integer GMax:', TFakeClassInt.gmax( 23, 56 ) ); | |
| 33 | + | // show max of two doubles | |
| 34 | + | writeln( 'Double GMax:', TFakeClassDouble.gmax( 23.89, 56.5) ); | |
| 35 | + | readln(); | |
| 36 | + | end. | |
| 37 | + | ``` | |
| 38 | + | ||
| 39 | + | --- | |
| 40 | + | *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](/wiki-contact).* |
