Thread overview | |||||
---|---|---|---|---|---|
|
July 19, 2015 static-if cant compile | ||||
---|---|---|---|---|
| ||||
Pardon me for trivial question, Am new to D. Why would a statement as below fail to compile. The plan is to do some computation at compile-time hence considering the static-if statement which fails to compile. The regular if-statement compiles but is not useful since it is a runtime construct. The error message I get is : Error: variable i cannot be read at compile time foreach( i; 0..size-1){ static if ( i == -1 ){ //Do something } } |
July 19, 2015 Re: static-if cant compile | ||||
---|---|---|---|---|
| ||||
Posted in reply to Clayton | On 20/07/2015 12:17 a.m., Clayton wrote:
> Pardon me for trivial question, Am new to D.
>
>
> Why would a statement as below fail to compile. The plan is to do some
> computation at compile-time hence considering the static-if statement
> which fails to compile. The regular if-statement compiles but is not
> useful since it is a runtime construct.
>
> The error message I get is : Error: variable i cannot be read at
> compile time
>
>
>
>
> foreach( i; 0..size-1){
> static if ( i == -1 ){
> //Do something
> }
>
> }
static if is for compile time known constants.
if is for runtime variables.
In this case it would be a runtime variable even if it is known at compile time.
Known at compile time != run at compile time. They overlap yes, just not the same thing.
|
July 19, 2015 Re: static-if cant compile | ||||
---|---|---|---|---|
| ||||
Posted in reply to Clayton | On Sunday, 19 July 2015 at 12:17:04 UTC, Clayton wrote:
> Pardon me for trivial question, Am new to D.
In D, you can run regular runtime code at compile time in a lot of cases. Just write an ordinary function that returns the data you need, then use it in a static variable initialization.
// example function, notice regular if and variables inside
int calculate(int i) { if(i < 0) return -i; else return i; }
static int value = calculate(5); // this is run at compile time
Ordinary functions will be interpreted if asked for their result in a context that only can be run at compile time, like a static variable initialization or inside a static if.
|
Copyright © 1999-2021 by the D Language Foundation