Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2016-09

generic way of writing Sets or Enum values to a String

4 messages · 3 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Graeme Geldenhuys

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

Reply by email

leledumbo
to Graeme Geldenhuys
Show quoted text 6 lines
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?

Take mine:

generic function EnumValueNameOf<T>(v: T): String;
begin
  Result := GetEnumName(TypeInfo(T), LongInt(v));
end;

guess you already know how to use it, don't you?

Reply by email