Sign in Join
Wiki copytemporary

How to use generics: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: How to use generics

OldNewLine
1+An example of how to use generics to write a `function gmax()` that takes the maximum of two not-yet-typed [[Variable|variables]]. Note that while the functions here are namespaced by the classname, FPC versions from 3.1.1 onwards also support fully free-standing generic methods.
2+
3+``` pascal
4+program UseGenerics;
5+
6+{$mode objfpc}{$H+}
7+
8+type
9+ generic TFakeClass<_GT> = class
10+ class function gmax(a,b: _GT):_GT;
11+ end;
12+
13+ TFakeClassInt = specialize TFakeClass<integer>;
14+ TFakeClassDouble = specialize TFakeClass<double>;
15+
16+ class function TFakeClass.gmax(a,b: _GT):_GT;
17+ begin
18+ if a > b then
19+ result := a
20+ else
21+ result := b;
22+ end;
23+
24+begin
25+ // show max of two integers
26+ writeln( 'Integer GMax:', TFakeClassInt.gmax( 23, 56 ) );
27+ // show max of two doubles
28+ writeln( 'Double GMax:', TFakeClassDouble.gmax( 23.89, 56.5) );
29+ readln();
30+end.
31+```
32+
33+---
34+*From the Free Pascal wiki, page "How to use generics", as it stood on 2023-09-20 after a change by RogueScholar, 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).*

Back to history