using enums as key in associative array

spir denis.spir at gmail.com
Tue Mar 8 04:54:45 PST 2011


On 03/08/2011 09:26 AM, Wilfried Kirschenmann wrote:
>>> enum deviceType {cpu, gpu}
>>> auto execDeviceSuffix = [deviceType.cpu:".cpu", deviceType.gpu:".gpu"];
>
>> The way to get what you want to work in this case is to use a module
>> constructor. So, you'd do something like this:
>>
>> string[deviceType] execDeviceSuffix;
>>
>> static this()
>> {
>>         execDeviceSuffix[deviceType.cpu] = "cpu";
>>         execDeviceSuffix[deviceType.gpu] = "gpu";
>> }
>>
>> The module constructor will be run before main does, so execDeviceSuffix will be
>> properly filled in by then.
>
> I didn't get to the point where module constructors are introduced in
> Andrei's book yet. I really like this idea !
> I found a similar workaround which used an useless class so that I
> could use the static constructor but this is even better !

This is a very nice feature, yes. But I personly see it as a workaround for the 
limitation that dmd, apparently, is not able to correctly evaluate many kinds 
of assignment expressions. And it's ugly when one has hordes of definitions -- 
the module is (mainly) a piece of data description: all symbols must first be 
declared /outside/, then redefined /inside/ static this(). Else, D would be a 
great data-definition language, in addition to its other qualities, thank to 
its literals for everything (and conversely its standard to!string for 
everything, which needs improvements). Think a static Lua.

Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d-learn mailing list