CharInSet Compiler Warning in Delphi XE4

前端 未结 3 528
甜味超标
甜味超标 2021-02-06 10:25

I have following statement in my Delphi 7 code.

TMyCharSet = set of char;

When I migrated that code to Delphi XE4, I am getting following compi

3条回答
  •  不要未来只要你来
    2021-02-06 11:03

    You get the warning because XE4 uses WideChar for variable of Char type (and WideString for String), so Char takes 2 bytes instead of 1 byte now. Now it is possible to keep unicode characters in String/Char, but for same reason it is impossible to use set of char anymore (in Delphi it is fixed size, 32-bytes bits map and can keep up to 256 items so).

    If you use only chars from range #0..#127 (only latin/regular symbols), then you can just replace Char -> AnsiChar (but when you will assign it from Char you will see another warning, you will have to use explicit type conversion to suppress it).

    If you need national/unicode symbols, then there is no "ready to use" structure in Delphi, but you can use Tdictionary for this purpose:

    type
      TEmptyRecord = record end;
    
      TSet = class(TDictionary)
      public
        procedure Add(Value: T); reintroduce; inline;
        procedure AddOrSetValue(Value: T); reintroduce; inline;
        function Contains(Value: T):Boolean; reintroduce; inline;
      end;
    
    procedure TSet.Add(Value: T);
    var Dummy: TEmptyRecord;
    begin
      inherited AddOrSetValue(Value, Dummy);
    end;
    
    procedure TSet.AddOrSetValue(Value: T);
    var Dummy: TEmptyRecord;
    begin
      inherited AddOrSetValue(Value, Dummy);
    end;
    
    function TSet.Contains(Value: T): Boolean;
    begin
      result := inherited ContainsKey(Value);
    end;
    

    Of course you will have initialize at as any other regular class. But it will be still quite efficient (not so fast as "set of" of course, just because "set" is always limited by 256 items max size but highly optimized).

    Alternatively you can create your own set class for unicode chars as map of bits, it will take 8kb of memory to keep all the bits and will be almost as fast as "set of".

提交回复
热议问题