constructing module level immutable variables at runtime?

Ali Çehreli via Digitalmars-d digitalmars-d at puremagic.com
Sun Feb 21 23:14:25 PST 2016


On 02/21/2016 10:55 PM, Danni Coy via Digitalmars-d wrote:
> I am trying to port a heavily multithreaded C++ application to D.
>
> I have a lot of variables that are set once from a config file at
> runtime and then never change.
> It seems that something like the following would be a very clean design.
>
> module config;
>
> static this()
> {
>      num_triggers = to!int(getValueFromConfigFile());
> }
>
> private:
> immutable(int) num_triggers = void;
>
> Is there any reason that allowing this would be a bad idea?
>

There is import() to read a config file at compile time:

module config;

string getValueFromConfigFile() {
     // Assume 'config_file' has just "42" in it:
     auto file_content = import("config_file");
     return file_content;
}

static this()
{
     import std.conv : to;
     num_triggers = to!int(getValueFromConfigFile());
}

private:
immutable(int) num_triggers;    // NOTE: '= void' did not work here

void main() {
     assert(num_triggers == 42);
}

Ali



More information about the Digitalmars-d mailing list