Unreachable warning is annoying
Steven Schveighoffer
schveiguy at yahoo.com
Tue Mar 13 17:32:55 UTC 2018
On 3/13/18 12:50 PM, Yuxuan Shui wrote:
> On Tuesday, 13 March 2018 at 14:40:21 UTC, Steven Schveighoffer wrote:
>> On 3/13/18 10:25 AM, Yuxuan Shui wrote:
>>> [...]
>>
>> This has been discussed before. There are a few ways around this. One
>> is to do what you did. Another is to append a sentinel, or use id to
>> terminate the loop:
>>
>> foreach(id, R; S) {
>> static if(is(T == R))
>> return id;
>> else static if(id + 1 == S.length)
>> return -1;
>> }
>
> Wait, I don't understand how this works.
>
> Isn't this going to be expanded to something like:
>
> return 0;
> return 4;
> // One return for every match
> ....
> return -1;
>
> Shouldn't this trigger unreachable warning too?
Yes, it's going to trigger one return for every match, and the return
for -1.
But there is something special about an unrolled foreach. Notice, it's
NOT a static foreach. A static foreach would result in the same problem.
An unrolled foreach on a tuple has a notion that the flow control jumps
out of the loop, and it's OK to skip further loops (even though they are
technically unrolled).
This works for break and continue as well. It's a very convoluted
notion, one that is hard to grasp and explain.
In any case, the better solution would be if the compiler turned off the
"unreachable statement" detection when it encountered a static if based
on template parameters.
-Steve
More information about the Digitalmars-d
mailing list