1

My code:

function  Str2Dbl(const str: string; var v: double): boolean;
var
  dp: integer;
  cstr: string;
  xv: extended;
begin
  if FormatSettings.DecimalSeparator <> '.' then
  begin
    dp := pos('.', str);
    if dp <> 0 then
    begin
      cstr := str;
      cstr[dp] := FormatSettings.DecimalSeparator;
    end
    else
      cstr := str;
  end
  else
    cstr := str;
  if cstr <> '' then
    result := TextToFloat(@cstr[1], xv, fvExtended, FormatSettings)
  else
    result := false;
  if result then
    v := xv;
end;

In Delphi 10.2 it gives an error:

[dcc32 Error] commutil.pas(1005): E2251 Ambiguous overloaded call to 'TextToFloat'
      System.SysUtils.pas(18332): Related method: function TextToFloat(PWideChar; var; TFloatValue; const TFormatSettings): Boolean;
      System.SysUtils.pas(18515): Related method: function TextToFloat(PAnsiChar; var; TFloatValue; const TFormatSettings): Boolean;

I do not understand how to fix this error!!!

1 Answer 1

4

The error is because @cstr[1] has type Pointer and the overload resolution does not know which overload (PAnsiChar or PWideChar) you want.

In any case, using @cstr[1] is wrong in general, and will fail with a runtime error if cstr is empty. Use PChar(cstr) instead. This will also allow the overload resolution to work.

I appreciate that you test whether or not cstr is empty, but that test is not necessary if you use the magic of the PChar(...) cast. Even when the string is empty, PChar(...) gives a valid pointer to a null-terminated character array.

The documentation is worth consulting on this subject. The key statement is:

PChar(S) always returns a pointer to a memory block; if S is empty, a pointer to #0 is returned.

So, you will be able to replace:

if cstr <> '' then
  result := TextToFloat(@cstr[1], xv, fvExtended, FormatSettings)
else
  result := false;

which did not compile anyway, with:

result := TextToFloat(PChar(cstr), xv, fvExtended, FormatSettings)

which does compile and avoids that if statement boiler-plate.

Aside

I initially expected that enabling typed address operator with {$T+} would make @cstr[1] be a typed pointer and help the overload resolution. However, that is not the case. It was surprising to me that this program compiles:

{$T+}

var
  PA: PAnsiChar;
  PW: PWideChar;
  s: string;

begin
  PA := @s[1];
  PW := @s[1];
end.

The linked documentation says:

When @ is applied to a variable reference in the {$T+} state, the type of the result is ^T, where T is compatible only with pointers to the type of the variable.

This seems to be contradicted by

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.