Einzelnen Beitrag anzeigen

Benutzerbild von Stevie
Stevie

Registriert seit: 12. Aug 2003
Ort: Soest
4.011 Beiträge
 
Delphi 10.1 Berlin Enterprise
 
#5

AW: Generic Integer zu Float konvertieren

  Alt 22. Dez 2017, 13:40
Delphi-Quellcode:
function TMyRec<T>.ToDouble: Double;
begin
  case GetTypeData(TypeInfo(t)).OrdType of
    otSByte: Result := PShortInt(@v)^;
    otUByte: Result := PByte(@v)^;
    otSWord: Result := PSmallInt(@v)^;
    otUWord: Result := PByte(@v)^;
    otSLong: Result := PInteger(@v)^;
    otULong: Result := PCardinal(@v)^;
  end;
end;
Das wäre von der Idee her perfekt, aber ist das intrinsisch, oder erzeugt das Runtime-Overhead?
Leider bisschen runtime overhead.
Wenn du genau weißt, dass dein T nur von den 6 System Typen ist und nicht von irgendwelchen Redeklarationen a la type TColumnIndex = type Integer dann kannst du auch das hier schreiben - TypeInfo vergleiche werden seit XE7 zur Compilezeit aufgelöst (kannst auch beides kombinieren so, dass du schnell bist, wenns Integer, Byte etc ist und wenn nicht auf die langsamere Variante zurück fällst)

Delphi-Quellcode:
function TMyRec<T>.ToDouble: Double;
begin
  if TypeInfo(T) = TypeInfo(ShortInt) then
    Result := PShortInt(@v)^
  else if TypeInfo(T) = TypeInfo(Byte) then
    Result := PByte(@v)^
  else if TypeInfo(T) = TypeInfo(SmallInt) then
    Result := PSmallInt(@v)^
  else if TypeInfo(T) = TypeInfo(Word) then
    Result := PWord(@v)^
  else if TypeInfo(T) = TypeInfo(Integer) then
    Result := PInteger(@v)^
  else if TypeInfo(T) = TypeInfo(Cardinal) then
    Result := PCardinal(@v)^
  else if TypeInfo(T) = TypeInfo(UInt64) then
    Result := PUInt64(@v)^
  else if TypeInfo(T) = TypeInfo(Int64) then
    Result := PInt64(@v)^
  else
    case GetTypeKind(T) of
      tkInteger:
        case GetTypeData(TypeInfo(t)).OrdType of
          otSByte: Result := PShortInt(@v)^;
          otUByte: Result := PByte(@v)^;
          otSWord: Result := PSmallInt(@v)^;
          otUWord: Result := PWord(@v)^;
          otSLong: Result := PInteger(@v)^;
          otULong: Result := PCardinal(@v)^;
        end;
      tkInt64:
        if GetTypeData(TypeInfo(T)).MinInt64Value = 0 then
          Result := PUInt64(@v)^
        else
          Result := PInt64(@v)^;
    end;
end;
Stefan
“Simplicity, carried to the extreme, becomes elegance.” Jon Franklin

Delphi Sorcery - DSharp - Spring4D - TestInsight

Geändert von Stevie (22. Dez 2017 um 13:50 Uhr)
  Mit Zitat antworten Zitat