Making recursively-defined traits iterative using `static foreach`

Simen Kjærås simen.kjaras at gmail.com
Sat Mar 10 18:26:48 UTC 2018


On Saturday, 10 March 2018 at 13:30:18 UTC, Nordlöw wrote:
> On Saturday, 10 March 2018 at 09:47:55 UTC, Nordlöw wrote:
>> Now that we have `static foreach` I just realized we can 
>> start...
>
> My recent definition now looks like
>
> template allSameTypeIterative(V...)
> // TODO restrict `V` to types only
> {
>     static if (V.length <= 1)
>     {
>         enum allSameTypeIterative = true;
>     }
>     else
>     {
>         static foreach (Vi; V[1 .. $])
>         {
>             static if (!is(typeof(allSameTypeIterative) == 
> bool) && // not yet defined
>                        !is(V[0] == Vi)) // 10% faster than 
> `!isSame(V[0], Vi)`
>             {
>                 enum allSameTypeIterative = false;
>             }
>         }
>         static if (!is(typeof(allSameTypeIterative) == bool)) 
> // if not yet defined
>         {
>             enum allSameTypeIterative = true;
>         }
>     }
> }
>
> Is there a way to break the `static foreach` loop prematurely 
> as quickly as `allSameTypeIterative` becomes false?

Sure:

@property
bool allSameTypeIterative(V...)()
//if (allSatisfy!(isType, V))
{
     foreach (Vi; V)
         if (Vi != V[0]) return false;
     return true;
}

No, it's not quite the same, but it's easier to read and gives 
the same result.

--
   Simen


More information about the Digitalmars-d mailing list