[D.typesystem] Static (CT) enforce anybody?

Steven Schveighoffer schveiguy at yahoo.com
Wed Sep 1 06:19:38 PDT 2010


On Wed, 01 Sep 2010 09:03:39 -0400, Justin Johansson <no at spam.com> wrote:

> IIRC std.contracts has been deprecated and replaced by std.exception,
> enforce and friends.  The latter are runtime things, correct(?).
>
> Is there a valid use case for compile-time (i.e. subject to static
> analysis) design-by-contract (DBC) enforce-like machinery?
>
> For example, and perhaps not the best example, one might like to pass
> an array of Foos to a function which by static design expects to
> receive such array at runtime as containing a minimum and/or maximum of
> elements.  Should (i.e. could it be desirable that) such interface
> contracts be checkable at compile-time?

Compile time checks are only available for compile time values.  If you  
have a function like this:

void foo(int[] x)

There is no way at compile time to check whether x has a maximum or  
minimum number of elements. But if you have something like this:

void foo(uint N)(ref int[N] x)

Then you can check N, because it is a compile-time value.  you can make  
checks via template constraints or static assert statements:

void foo(uint N)(ref int[N] x) if(N >= minvalue)

- or -

void foo(uint N)(ref int[N] x)
{
    static assert(N >= minvalue, "Error, invalid sized array passed to  
foo");
}

Both of these will fail to compile if you pass incorrect data.

-Steve


More information about the Digitalmars-d mailing list