On 7/10/18 7:38 AM, kdevel wrote:
On Tuesday, 10 July 2018 at 00:11:27 UTC, Steven Schveighoffer wrote:
On 7/7/18 7:28 AM, kdevel wrote:
It appears not to be possible to use static if in "guard clause style" as in

    void bar (T ...) (T args)
    {
       static if (args.length == 0)
          return;

       writeln (args [0]);
       return bar (args [1 .. $]);
    }

Is this intended?

Yes.

Try just a normal if -- it will have the same effect (the optimizer will eliminate the dead code), but will compile.

I would like to suggest an extension of the language by introducing

     static return Expression_opt;

which shall have the effect of a return plus that the remaining lines in the current block are treated as if they were enclosed in an else block.
I think it's simpler than that. IMO, any time you have a static if that uses template parameters, it should be treated for purposes of detecting unreachable code as if it were a normal if statement. To the user "unreachable" code means it never can be reached. But that code CAN be reached with different compile-time parameters.

Your anecdote is easy to solve, but it's much more difficult to do something like this in a static loop.

I don't want to introduce more syntax, this is basically a lint error.

Of course, you have to fix your second part to only return bar if args.length > 0!

This violates DRY. Same problem as with the template constraints version where the condition used in every special case has to be repeated in the general case.

Sorry, but it has to try to compile this, and args[1 .. $] is invalid at compile time.

You can get it back to being DRY by using else.

-Steve

Reply via email to