How to set default value for a function parameter of type TEncoding?

Converting from D2007 to XE2, I converted this function

function Add_Line( FileStream : TFileStream; ALine : string) : boolean;

to

function Add_Line( FileStream : TFileStream; ALine : string; Enc: TEncoding = nil) : boolean;
var
  AStr: ANSISTring;
begin
  Result := True;
  if Enc = nil then Enc := TEncoding.ANSI;
  try
//Old    FileStream.WriteBuffer( Pointer(ALine)^, Length(ALine) );
    if Enc = TEncoding.UTF8 then
      AStr := UTF8Encode(ALine)
    else
      AStr := ANSIString(ALine);
    FileStream.WriteBuffer( AStr[1], Length(ALine) );
    end;
  except
    Result := False;
  end;
end;

Rationale:

  • Change code using Add_Line as little as possible

  • Accept the automatic change to Unicode, only at the last moment write 8-bit text files (this is used in XML and CSV). In the future we could still move to UTF-16 files if we want.

I would have liked to define something like:

function Add_Line( FileStream : TFileStream; ALine : string; Enc: TEncoding = TEncoding.ANSI) : boolean;

but the compiler complains ;-)

Is anything like that possible?

Answers


Default arguments must be a compile-time constant, but if you need anything more advanced, you can create overloads:

function Add_Line( FileStream : TFileStream; ALine : string) : boolean; overload;
function Add_Line( FileStream : TFileStream; ALine : string; Enc: TEncoding) : boolean; overload;


function Add_Line( FileStream : TFileStream; ALine : string) : boolean;
begin
  Result := Add_Line(FileStream, ALine, TEncoding.ANSI);
end;

You can even add the inline keyword to get exactly the same generated code that the default argument would have resulted in, were it valid.

Note: you don't seem to support anything other than TEncoding.ANSI and TEncoding.UTF8. In that case, a TEncoding parameter seems overkill, you could use a UTF8: Boolean parameter instead (or rework your code to work with an arbitrary encoding's CodePage).

Note 2: FileStream.WriteBuffer( AStr[1], Length(ALine) ); is wrong because Length(ALine) and Length(AStr) need not be the same, you should use Length(AStr) instead. Also, AStr[1] can result in an exception when AStr is an empty string, you can add a special case to only call WriteBuffer when AStr is not empty.


Need Your Help

Is it possible to replace NL join with HS join in sql

sql db2 query-optimization

Hi am having a very big query comprises of two main table and 15 sub tables.

Google Developer Console Doesn't List Mail API

oauth-2.0 google-api gmail google-oauth gmail-imap

The Google Developer Consoles (even the old version) no longer lists the Mail API in the list of available APIs.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.