I found a trick to test conversion between 2 types in compile time (found in C++ Super Book "Modern C++ Design" by Andrei Alexandrescu)

I found a trick to test conversion between 2 types in compile time  (found in C++ Super Book "Modern C++ Design" by Andrei Alexandrescu)

type
  Small = Char;
  Big   = Integer;

  ConversionCore = class
  public
    class function Test(const Dummy:U):Small;overload;static;
    class function Test(const Dummy):Big;overload;static;
  end;

  Conversion = class
  public
    class function IsExists():boolean;static;inline;
  end;

class function ConversionCore.Test(const Dummy: U): Small;
begin
end;

class function ConversionCore.Test(const Dummy): Big;
begin
end;

// doesn't work
class function Conversion.IsExists: boolean;
type
  ConvertType = ConversionCore;
var
  Dummy:T;
begin
  Result := Sizeof(ConvertType.Test(Dummy)) = Sizeof(Small);
end;

// Test
procedure TForm1.Button2Click(Sender: TObject);
type
  BaseType = TList;
  ConvertType = ConversionCore;
var
  T:BaseType;
begin
  case Sizeof(ConvertType.Test(T)) = Sizeof(Small) of
    true:  begin
             ShowMessage('Conversion ok'); // OK!!!!!! Cool!
           end;
    false: begin //  compiler remove this part
             ShowMessage('Conversion error');
           end;
  end;

  if Conversion.IsExists then
    ShowMessage('Conversion ok')
  else ShowMessage('Conversion error');   //FALSE!!!!!

end;

but it doesn't works in generic class !
a solution ? any idea/suggestion ?

Comments

  1. Stefan Glienke thanks! I saw delphi is not c++. unfortunately!

    ReplyDelete
  2. Michel Podvin - I have to say that it is fortunate that Delphi is not C++ :)
    This bug is unfortunate, though.

    ReplyDelete
  3. Stefan Glienke Thanks for the link. I couldn't make sense of the Delphi code; the C++ article made much more sense. (Can't say I'm a fan of everything in the article, but the third and last tip, ie the one this code was based on, is actually rather neat.)

    ReplyDelete

Post a Comment