How to make a static immutable associative array using assocArray in CT?

realhet real_het at hotmail.com
Tue Feb 10 20:46:11 UTC 2026


Hi,

This is the error message I got:

     
/dlang/dmd/linux/bin64/../../src/druntime/import/object.d(2922): 
Error: `_d_assocarrayliteralTX` cannot be interpreted at compile 
time, because it has no available source code
         return _d_assocarrayliteralTX(typeid(Value[Key]), 
*cast(void[]*)&keys, *cast(void[]*)&values);

The source:
```d
     import std;

     enum EnumMemberNames(T) = is(T==enum) ? [__traits(allMembers, 
T)] : [];

     class AMDB
     {
     	enum SysType {
     		Entity, String, Int, Bool, Float, Double, DateTime, Date, 
Time
     	}

     	static immutable
     		sysTypeNames = EnumMemberNames!SysType,
     		sysTypes = [EnumMembers!SysType],
         	sysTypeNameMap2 = assocArray(sysTypeNames, true.repeat) 
//works
     //fails    	sysTypeNameMap3 = assocArray(sysTypeNames, 
[EnumMembers!SysType]) //fails!!!!!!
         ;

         //works and ugly
         mixin(`static immutable sysTypeNameMap4 = 
[`~sysTypeNames.map!((string 
a)=>(`"`~a~`":SysType.`~a)).join(',')~`];`);
     	
     	//also works
         static auto sysTypeNameMap()
     	{
     		static immutable(SysType)[immutable(string)] this_is_bad;
     		if(this_is_bad.empty) this_is_bad = 
assocArray(sysTypeNames, sysTypes);
     		return this_is_bad;
     	}
     }

     void main()
     {
     	AMDB.sysTypeNameMap.writeln;
         AMDB.sysTypeNameMap4.writeln;
     }
```

I only managed to make it when the value range is simple as 
`true.repeat` or when I generate the whole static immutable 
declaration by a mixin().

Is there a better way?


More information about the Digitalmars-d-learn mailing list