Skip to content

Instantly share code, notes, and snippets.

@jpluimers
Last active March 13, 2021 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpluimers/c1c5e68dc94891e10d454814c824e38c to your computer and use it in GitHub Desktop.
Save jpluimers/c1c5e68dc94891e10d454814c824e38c to your computer and use it in GitHub Desktop.
In Delphi, you cannot do math with generic types, as you will get "E2015 Operator not applicable to this operand type" because there is no way to constraint the generic type to be floating point or ordinal.
unit AxisUnit;
interface
type
TAxis<T: record> = record
fMin, fMax, fRange: T;
fStart, fEnd, fExtent: single;
function CalcCasted( const AScalar: T ): single;
function CalcPlain( const AScalar: T ): single;
end;
implementation
function TAxis<T>.CalcCasted(const AScalar: T): single;
var
Offset: single;
NormalisedOffset: single;
ScaledOffset: single;
begin
// First 2 lines give the same error: E2089 Invalid typecast
Offset := single(AScalar) - fMin;
NormalisedOffset := Offset / single(fRange);
ScaledOffset := NormalisedOffset * fExtent;
Result := fStart + ScaledOffset;
end;
function TAxis<T>.CalcPlain(const AScalar: T): single;
var
Offset: T;
NormalisedOffset: T;
ScaledOffset: T;
begin
// All 4 lines give the same error: E2015 Operator not applicable to this operand type
Offset := AScalar - fMin;
NormalisedOffset := Offset / fRange;
ScaledOffset := NormalisedOffset * fExtent;
Result := fStart + ScaledOffset;
end;
end.
program DelphiMathAndGenerics;
uses
AxisUnit in 'AxisUnit.pas';
var
rXAxis: TAxis<TDateTime>;
rYAxis: TAxis<single>;
begin
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment