Difference between revisions of "How to use generics"

From Free Pascal wiki
Jump to navigationJump to search
(extracted from Howto Use Interfaces)
 
m (Replace deprecated 'enclose' attribute in syntaxhighlight tags with current 'inline' attribute)
 
(4 intermediate revisions by 3 users not shown)
Line 1: Line 1:
An example of how to use generics to write a function gmax() that takes the maximum of two not-yet-typed variables.
+
An example of how to use generics to write a <syntaxhighlight lang="pascal" inline>function gmax()</syntaxhighlight> 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.
Note that the functions are namespaced by the classname. A disadvantage may be that generics can't be overloaded.
+
<syntaxhighlight lang="pascal">
 
 
<syntaxhighlight>
 
 
program UseGenerics;
 
program UseGenerics;
  
Line 30: Line 28:
 
   readln();
 
   readln();
 
end.
 
end.
</syntaxhighlight>
+
</syntaxhighlight><noinclude>
 +
 
 +
 
 +
[[Category:Tutorials]]</noinclude>

Latest revision as of 23:17, 20 September 2023

An example of how to use generics to write a function gmax() that takes the maximum of two not-yet-typed 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.

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.