[fpc-devel] Little feature teaser

Anthony Walter sysrpl at gmail.com
Fri Aug 2 15:00:46 CEST 2013


Wow, that looks great Sven. I've been wanting generic functions for a long
time. Would it be possible to add constraints like must override operators
=, <, or > ... and possibly +, -, /, *, and, or, shl, shr, div, mod?

In this way you could write:

function Sum<T, Add>(const Items: TArray<T>): T;
var
  I: T;
begin
  Result := default(T);
  for I in T do
    Result := Result + T;
end;

I := Sum([1, 2]); // okay
S := Sum(['Hello', 'World']); // okay
V := Sum([Vec2(1, 2), Vec2(3, 4)]); // okay only if type TVec2 overloads
"operator TVec2.Add(const A, B: TVec2): TVec2;"

On Fri, Aug ?2, 2013 at 7:18 AM, Sven Barth <pascaldragon at googlemail.com>wrote:

> Hello together!
>
> Just a little feature teaser what I'm currently working on when I find the
> time. :)
>
> === source begin ===
>
> program tgenfuncs;
>
> {$modeswitch result}
>
> generic function IsIn<T>(aElement: T; const aArray: array of T): Boolean;
> var
>   elem: T;
> begin
>   for elem in aArray do
>     if elem = aElement then
>       Exit(True);
>   Result := False;
> end;
>
> begin
>   Writeln(specialize IsIn<LongInt>(42, [21, 42, 84]));
>   Writeln(specialize IsIn<LongInt>(5, [21, 42, 84]));
>   Writeln(specialize IsIn<String>('Foobar', ['Foo', 'Bar', 'Blubber']));
> end.
>
> === source end ===
>
> === console begin ===
>
> PS D:\svn\fpc> .\compiler\i386\pp.exe -n -Furtl\units\i386-win32
> -FEtestoutput -viwn .\fpctests\tgenfuncs.pas
> Target OS: Win32 for i386
> Compiling .\fpctests\tgenfuncs.pas
> Linking testoutput\tgenfuncs.exe
> 19 lines compiled, 0.3 sec, 32224 bytes code, 1204 bytes data
> PS D:\svn\fpc> .\testoutput\tgenfuncs.exe
> TRUE
> FALSE
> FALSE
>
> === console end ===
>
> Regards,
> Sven
> ______________________________**_________________
> fpc-devel maillist  -  fpc-devel at lists.freepascal.org
> http://lists.freepascal.org/**mailman/listinfo/fpc-devel<http://lists.freepascal.org/mailman/listinfo/fpc-devel>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20130802/dc16cbae/attachment.html>


More information about the fpc-devel mailing list