static if enhancement

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Thu Jun 30 04:06:56 PDT 2016


On 6/29/16 11:40 AM, Wyatt wrote:
> On Friday, 24 June 2016 at 18:27:07 UTC, Steven Schveighoffer wrote:
>> void fun(T)(T obj)
>> {
>>     static if (!hasMember(T, "gun")) throw new Exception("No gun");
>>     obj.gun;
>> }
>>
>> Call with something that doesn't have a gun member, and even without
>> the reachability warnings (no -w switch), it doesn't compile. However,
>> with an else clause, it would compile.
>
> I might be stepping on a land mine by bringing it up, but isn't this
> sort of thing what contracts are for?

No landmines here, but no, that isn't what contracts are for. Perhaps 
you mean constraints?

A constraint will prevent compilation vs. allowing compilation but 
emitting a failure at runtime. I agree this is a better mechanism, or 
just plain allow the compiler to make a proper error when you call gun.

It's not so much that this example is meant be a justification, but more 
an explanation of what the enhancement will do.

In any case, I've drifted back towards being against this change. It 
leaves the compilability of code up to the quality of the compiler's 
flow analysis.

-Steve


More information about the Digitalmars-d mailing list