Compile time initialization of AA
Patrick Schluter
Patrick.Schluter at bbox.fr
Sat Mar 24 10:43:34 UTC 2018
On Friday, 23 March 2018 at 22:43:47 UTC, Xavier Bigand wrote:
> I am trying to initialize an global immutable associative array
> of structs, but it doesn't compile.
> I am getting the following error message : "Error: not an
> associative array initializer".
>
> As I really need to store my data for a compile time purpose if
> we can't do that with AA, I'll use arrays instead.
>
> Here is my code :
> struct EntryPoint
> {
> string moduleName;
> string functionName;
> bool beforeForwarding = false;
> }
>
> immutable EntryPoint[string] entryPoints = [
> "wglDescribePixelFormat":
> {moduleName:"opengl32.forward_initialization",
> functionName:"wglDescribePixelFormat"}
> ];
Another solution, radically different is to not use an AA but a
simple array.
Instead of indexing on a string you could simply index on an enum
type. As your array is compile time constant, the dynamic nature
of AA is not really used and indexing on a enum value is faster
and simpler anyway.
The trick here is to generate the enum type at compile time. This
can be achieved by a string mixin built at compile time.
Here an example that I used to generate an enum from the values
from another enum. In your case you can look where the
"wglDescribePixelFormat" are defined and using imports or string
building code.
mixin({
string code = "enum LANBIT : ulong { "~
"init = 0,"; /* We set the dummy
init value to 0 */
foreach(lanCode; __traits(allMembers, LANIDX)) {
static if(lanCode == "IN")
code ~= "INVALID = LANIDX2LANID(LANIDX."~lanCode~"),";
else
code ~= lanCode~"= LANIDX2LANID(LANIDX."~lanCode~"),";
}
code ~= "
ALL = INVALID-1, /**< All bits except
the LANID_INVALID */
OFFICIAL=
BG|CS|DA|DE|EL|EN|ES|ET|FI|FR|GA|HR|HU|IT|LT|LV|MT|NL|PL|PT|RO|SK|SL|SV, /**< Official languages of the EU */
COOFFICIAL=CA|GL|EU|GD|CY /**< Co-official
languages of the EU */
";
return code ~ "}";
}());
TL/DR
defining constant compile time AA is an oxymoron. AA are by
nature dynamic runtime creatures. if the indexes are compile
time, a normal array with fixed indexes is enough.
More information about the Digitalmars-d-learn
mailing list