To take an example, lets say I would like to write a simple procedure that deletes the 'X' characters from a string.
How can I design my procedure so that it works for both string and PCHAR parameters.
If I define it as:
procedure RemoveX( source : PCHAR);
than calls to RemoveX(PCHAR(mystring)) where myString is a string will remove the 'X' but will not take care of updating the string length ... Hence a subsequent myString := myString + 'done' will leave myString unchanged. And I don't want to change the length after the call to RemoveX, I expect the RemoveX procedure to deal with everything.
If on the other hand I define it as:
procedure RemoveX( var source : string);
I don't know how to pass it a PCHAR ...
You cannot implement this using a single parameter. You have two different types.
You could build the string version on top of a
PCharversion.An alternative for final line could be:
Either way, this obviously assumes that you already have a functioning overload that operates on
PChar. And that the function removes characters. Clearly it cannot extend thePCharbuffer.The call to
UniqueStringis needed in case the string is shared (ref count greater than one) or constant. After this call the string buffer is editable and not shared.Whether or not avoiding duplication of implementation in this way is the best approach I cannot say. It depends on your design drivers. If simplicity and clarity of code is key, then avoiding duplication makes sense. If performance is key then it may be desirable to provide two bespoke implementations.