How to enforce compile time evaluation (and test if it was done at compile time)

Dukc via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 27 11:44:02 PST 2017


On Monday, 27 February 2017 at 19:26:06 UTC, Christian Köstlin 
wrote:
> Is it enough to put up static immutable modifiers?
> How can I make sure, that the calculations are done at compile 
> time?
>
> ...
> static immutable time = Unit("time", [Unit.Scale("ms", 1),
> ...

An initialization of a static variable (or constant, as in this 
case) is indeed always done at compile time. Another option would 
be using an enum storage class. Difference between enum and 
static or shared immutable is that enum IS a compile time 
constant, not just a runtime constant initialized at 
compile-time. That means you can use enums to calculate other 
compile-time stuff.

Template parameters are also calculated at compile time. If they 
take a value, they are enum values, only difference to normal 
enums being that their values are defined at template call site. 
Thus, if you pass an expression to a template argument, you can 
be sure it's calculated at compile time.


More information about the Digitalmars-d-learn mailing list