Solution to "statement is not reachable" depending on template variables?
Johan Engelen via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Apr 1 02:39:54 PDT 2016
On Friday, 1 April 2016 at 01:21:32 UTC, Walter Bright wrote:
> On 3/16/2016 4:18 AM, Johan Engelen wrote:
>> I've found discussions, but not an actual "recommended"
>> solution for the
>> problem of "statement is not reachable" warnings in templates
>> with early
>> returns, e.g.:
>> ```
>> bool nobool(T...)() {
>> foreach (i, U; T) {
>> static if (is(U == bool)) {
>> return false;
>> }
>> }
>> return true; // emits "Warning: statement is not
>> reachable"
>> }
>
>
> bool nobool(T...)() {
> bool result = true;
> foreach (i, U; T) {
> static if (is(U == bool)) {
> result = false;
> break;
> }
> else
> {
> ...
> }
> }
> return result; // emits "Warning: statement is not
> reachable"
> }
As you can see from my first post, that is the solution I used
first (without the "break;" addition), but it works until...
> Note that the optimizer will remove the dead loads.
... until someone adds a (imho useful) diagnostic of dead
stores/loads. :-)
In that case, I guess inverting all bools and then inverting the
return value at the end will work (using default initialization
of result); but this is not possible in a slightly more
complicated case with non-bool return types.
In another piece of code, the return type is a struct with an
immutable member. That's when I gave up on working around the
warning and just disabled it.
Simplified, something like this:
struct IMM {
immutable bool result;
}
IMM immut(T...)() {
IMM retval = IMM(true);
foreach (i, U; T) {
static if (is(U == bool)) {
retval = IMM(false); // "Error: cannot modify
struct retval IMM with immutable member".
}
}
return retval;
}
More information about the Digitalmars-d-learn
mailing list