Fixing spurious "statement is not reachable" in template code

tsbockman via Digitalmars-d digitalmars-d at puremagic.com
Tue Oct 27 22:29:05 PDT 2015


On Wednesday, 28 October 2015 at 03:38:37 UTC, Daniel Murphy 
wrote:
> I personally like the style of that code, and agree that it 
> allows less repetition.  But it does this at the cost of 
> intentionally introducing dead code in some instantiations.  If 
> you enable the compiler warnings about dead code, they have to 
> trigger here because it doesn't know if you introduced dead 
> code intentionally or not.  As is often the case with warnings, 
> if you want your code to compile with them you sometimes need 
> to avoid otherwise completely valid constructs.
>
> Here's a similar example:
>
> bool func(T, T val)()
> {
>     if (val < 0)
>         return true;
>     return false;
> }
>
> func!(uint, 7);
> func!(int, 7);
>
> When instantiated with uint, the first return is unreachable 
> because unsigned numbers cannot be negative.  When val == 7, 
> it's also unreachable because 7 is not less than 0.  Which 
> instantiations should give the warning?

I would say none, since *the template* contains no unreachable 
code, and the compiler can easily trim unreachable code from any 
*instantiation* which needs it, without bothering me about it.

I would only be interested in a warning if the compiler wasn't 
able to trim the dead code, but as far as I can tell the only 
case in which the compiler doesn't trim it, is the case where it 
doesn't realize it's unreachable - in which case it can't warn 
me, either.

> > Another perspective, though, which I picked up from someone
> (Andrei
> > Alexandrescu, I think?) in the D community, is to consider
> template
> > parameters simply as additional function arguments, which
> happen to
> > be evaluated at compile time. In many cases, the timing of
> their
> > evaluation is just an implementation detail - a performance
> > optimization (or de-optimization, as the case may be).
>
> This is a great way to learn how to use templates, but there 
> are limits to how well this simplification corresponds to 
> reality and this is one of them.  Parameters inhibit 
> optimizations and analysis in ways that compile-time constants 
> do not.

It's not intended as a simplification for people who can't handle 
the true complexity of templates - the difference is 
philosophical. It's a recognition of the fundamental unity of 
run-time and compile-time computation, the same idea which 
motivates CTFE.

If most people actually *want* these warnings, then great - 
there's no bug.
But, if most find the warnings conflict with how they want to use 
templates, as I do - why not just change it?

The "reality" of D templates is whatever the D community chooses 
to make it, subject to technical feasibility.


More information about the Digitalmars-d mailing list