best/proper way to declare constants ?
H. S. Teoh
hsteoh at quickfur.ath.cx
Thu Aug 5 03:20:17 UTC 2021
On Thu, Aug 05, 2021 at 01:39:42AM +0000, someone via Digitalmars-d-learn wrote:
[...]
> What happens in the following case ?
>
> public immutable enum gudtLocations = [
> r"BUE"d : structureLocation(r"arg"d, r"Buenos Aires"d, r"ART"d),
> r"GRU"d : structureLocation(r"bra"d, r"São Paulo"d, r"BRT"d),
> r"HHN"d : structureLocation(r"deu"d, r"Frankfurt am Main"d, r"CET"d),
> r"LHR"d : structureLocation(r"gbr"d, r"London"d, r"UTC"d),
> r"NYC"d : structureLocation(r"usa"d, r"New York"d, r"EST"d)
> ];
>
> This is something that I also need at compilation time.
[...]
If you need a constant array value both at compile-time and runtime, one
way to do it is to declare an enum that is used only by compile-time
code, and the same enum is used once to declare the runtime static
immutable.
Example:
enum ctValue = [ "my", "data", "here", ... ];
// Initialize this once with ctValue.
static immutable string[] rtValue = ctValue;
if (ctfe) {
// Compile-time: use ctValue
foreach (value; ctValue) {
...
}
} else {
// Runtime: use rtValue instead
foreach (value; rtValue) {
...
}
}
Just be sure you don't use ctValue during runtime, otherwise it will
incur an allocation per use.
T
--
What did the alien say to Schubert? "Take me to your lieder."
More information about the Digitalmars-d-learn
mailing list