[fpc-pascal] generic way of writing Sets or Enum values to a String

Graeme Geldenhuys mailinglists at geldenhuys.co.uk
Tue Sep 6 18:37:22 CEST 2016


Hi,

I use the following code which works fine, and I have many methods like
these for all the various Sets and Enum types I used.  I would like to
reduce my programming effort (such boilerplate code) by reusing maybe a
single implementation.

Is there a way to have a single implementation of Enum-to-String or
Set-to-String (and the reverse), but pass in the type, instead of having
a separate implementation of each Enum or Set types.

Could RTTI help? Could Generics help? Is there some other language
construct I might have missed?


function VisibleOnPageToString(AEnum: TFPReportVisibleOnPage): string;
inline;
begin
  result := GetEnumName(TypeInfo(TFPReportVisibleOnPage), Ord(AEnum));
end;

function StringToVisibleOnPage(AName: string): TFPReportVisibleOnPage;
inline;
begin
  Result :=
TFPReportVisibleOnPage(GetEnumValue(TypeInfo(TFPReportVisibleOnPage),
AName));
end;

function StringToMemoOptions(const AValue: string): TFPReportMemoOptions;
var
  lList: TStrings;
  lIndex: integer;
begin
  Result := [];
  lList := nil;
  lList := TStringList.Create;
  try
    lList.Delimiter := ',';
    lList.DelimitedText := AValue;
    for lIndex := 0 to lList.Count - 1 do
      Include(Result,
TFPReportMemoOption(GetEnumValue(TypeInfo(TFPReportMemoOption),
lList[lIndex])));
  finally
    lList.Free;
  end;
end;

function MemoOptionsToString(const AValue: TFPReportMemoOptions): String;
var
  lIndex: integer;
begin
  Result := '';
  for lIndex := Ord(Low(TFPReportMemoOption)) to
Ord(High(TFPReportMemoOption)) do
  begin
    if TFPReportMemoOption(lIndex) in AValue then
    begin
      if Result = '' then
        Result := GetEnumName(TypeInfo(TFPReportMemoOption), lIndex)
      else
        Result := Result + ',' +
GetEnumName(TypeInfo(TFPReportMemoOption), lIndex);
    end;
  end;
end;


Regards,
  Graeme

-- 
fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal
http://fpgui.sourceforge.net/

My public PGP key:  http://tinyurl.com/graeme-pgp



More information about the fpc-pascal mailing list