[fpc-pascal] Generic type conflicts

Cyrax evvke at hotmail.com
Sat Nov 2 16:06:22 CET 2019


On 02/11/2019 16:55, Ryan Joseph via fpc-pascal wrote:
> 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
> 
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
> 

You need to do a explicit typecasting.

...
fac:=Sqrt(Sqr(TScalar(x)) + Sqr(TScalar(y)));
...
fac:=1.0/TScalar(fac);



More information about the fpc-pascal mailing list