static assert(0) in template is a disaster

Tim tim.dlang at t-online.de
Wed Jun 17 15:38:36 UTC 2020


On Tuesday, 16 June 2020 at 23:01:10 UTC, Paul Backus wrote:
> ...but in fact, the existence of 'before' and 'after' states is 
> an unavoidable consequence of how `static if` works. The 
> condition of a `static if` statement *must* be evaluated before 
> the body is processed by the compiler. Without some mechanism 
> for controlling the order in which declarations undergo 
> semantic analysis, it would be impossible to implement `static 
> if` in the first place.

A similar problem can even happen, when porting C code to D, 
because D does not allow to use forward declarations.
Consider the following example:

const FOO_VER = 2;

static if(FOO_VER >= 2) // If Bar is defined
struct Bar {            // Foo should be defined too.
   Foo *foo;
}

static if(FOO_VER >= 1)
struct Foo {
}

It results in the following error:
Error: undefined identifier Foo, did you mean variable foo?

The equivalent C code would use a forward declaration of Foo, but 
that is not possible in D. Changing the order would work in this 
case, but would make it harder to port future changes from the C 
version. Using version instead of static if also solves the 
problem, but is less flexible.

The example is based on 
https://issues.dlang.org/show_bug.cgi?id=3743


More information about the Digitalmars-d mailing list