[Lazarus] New Graphics/Animation Library - Language Feature Requests

Sven Barth pascaldragon at googlemail.com
Fri Oct 12 12:24:27 CEST 2012


Am 11.10.2012 22:58, schrieb Anthony Walter:
> Okay, I looked into global operators a bit more and I think what you
> are referring to is objpas mode operator functions. If this is the
> case, then there is a problem because I don't believe objpas mode
> supports explicit conversions.
>

They do, see below.

> For clarity, I believe the correct intended use of explicit
> conversions is when a loss of data may occur while converting a type
> (rounding a float for example), and implicit conversions are correct
> when no loss of data can occur (assigning a 32bit integer to a 32bit
> float).
>
> type
>    Float = Single;
>    TPointI = TPoint<Integer>;
>    TPointF = TPoint<Float>;
>
> FloatPoint := IntPoint; // correct, no loss of data
> IntPoint := FloatPoint; // incorrect, data might be lost
> IntPoint := TPointI(FloatPoint); // okay, data might be lost but
> explicit conversion was used
>
> I don't think the above is currently possible given that you cannot
> define Implicit or Explicit operators on TPointI or TPointF since they
> are specialized from a generic record type (no inheritance).

If you don't know whether something works, you should just try it:

=== source begin ===

program asgnoptest;

{$mode objfpc}
{$modeswitch advancedrecords}

type
   generic TPoint<T> = record
     X, Y: T;
   end;

   TPointF = specialize TPoint<Single>;
   TPointI = specialize TPoint<LongInt>;

operator := (const Value: TPointI): TPointF;
begin
   Writeln('Implicit');
   Result.X := Value.X;
   Result.Y := Value.Y;
end;

operator Explicit(const Value: TPointF): TPointI;
begin
   Writeln('Explicit');
   Result.X := Round(Value.X);
   Result.Y := Round(Value.Y);
end;

var
   FloatPoint: TPointF;
   IntPoint: TPointI;
begin
   IntPoint.X := 21;
   IntPoint.Y := 42;

   FloatPoint := IntPoint;

   // No implicit from TPointF -> TPointI
   //IntPoint := FloatPoint;

   FloatPoint.X := 42.5;
   FloatPoint.Y := 21.25;

   IntPoint := TPointI(FloatPoint);

end.

=== source end ===

This compiles using 2.6.0. The output is (as expected):

=== output begin ===

Implicit
Explicit

=== output end ===

The only difference to operators in helpers would be that they aren't 
"grouped" in one structure.

That said: I'm not opposing your idea to allow operators in helpers (and 
classes) per se, but I just suggest you how you can acomplish your 
target with FPC's current features as I don't know when I'd get around 
to implement this.

Regards,
Sven




More information about the Lazarus mailing list