On 3/13/18 10:25 AM, Yuxuan Shui wrote:
See this simple example:
int staticFind(T, S...)() {
foreach(id, R; S) {
if (is(T == R))
return id;
}
}
return -1;
}
staticFind!(int, int, double) will generate a 'statement is unreachable'
warning, and staticFind!(int, double) won't.
This behaviour is understandable, but annoying. If template writer cares
about this unreachable warning, they basically can't use any early
return at all.
So previous example has to be re-written into:
int staticFind(T, S...)() {
int ret = -1;
foreach(id, R; S) {
if (is(T == R) && ret == -1)
ret = id;
}
}
return ret;
}
However, this might not always be so simple in more complex functions.
And this could potentially increase compilation time (maybe?).
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;
}
IMO, the "unreachable statement" error is bogus because it's reachable
depending on the template parameters! In the coder's eyes, what matters
is whether the line of source is reachable or not, not whether it's
reachable in that instantiation.
-Steve