rectifiedIndexOf()

apz28 apz28 at hotmail.com
Fri May 5 16:51:25 UTC 2023


On Friday, 5 May 2023 at 14:50:45 UTC, Salih Dincer wrote:
> On Friday, 5 May 2023 at 02:43:15 UTC, Basile B. wrote:
>> As often in D you can use a struct to help...
>> `opCast` is used for the `if` condition and the original value 
>> for reading back in the array, via `alias this`.
>
Or as below

     struct IndexOfResult
     {
         ptrdiff_t value;
         alias value this;

         bool opCast(T : bool)() const @nogc pure @safe
         {
             return value >= 0;
         }
     }

     void main()
     {
         import std.string : indexOf;
         import std.stdio : writeln, writefln;

         enum chr = 'a';
         enum arr = "dlang";
         if (auto res = IndexOfResult(arr.indexOf(chr)))
         {
             assert(arr[res] == chr);
             res.writefln!"[ --> %s ]";
         }
         else
             writeln("Not found!");
     }


More information about the Digitalmars-d mailing list