[fpc-pascal] Generic type conflicts
Ryan Joseph
genericptr at gmail.com
Sat Nov 2 15:55:16 CET 2019
I've wanted to make a generic version of a vector for a while but I always give up because it seems not very possible. It's probably not even a great idea because many methods don't translate between float and integer but I wanted to prevent other code duplication if possible.
Here's an example of how things break down. Are there any solutions for this currently? I feel like generics need to support some compiler directives so different blocks of code can specialize different depending on the type.
{$mode objfpc}
{$modeswitch advancedrecords}
program generic_vector_2;
uses
Math;
type
generic TVec2<TScalar> = record
x, y: TScalar;
function Normalize: TVec2;
end;
TVec2f = specialize TVec2<Float>;
TVec2i = specialize TVec2<Integer>;
function TVec2.Normalize: TVec2;
var
fac: TScalar;
begin
// Can't determine which overloaded function to call
// Incompatible types: got "Extended" expected "LongInt"
fac:=Sqrt(Sqr(x) + Sqr(y));
if fac<>0.0 then begin
// Incompatible types: got "Single" expected "LongInt"
fac:=1.0/fac;
result.x:=x*fac;
result.y:=y*fac;
end else begin
result.x:=0;
result.y:=0;
end;
end;
begin
end.
Regards,
Ryan Joseph
More information about the fpc-pascal
mailing list