using enums as key in associative array

Jonathan M Davis jmdavisProg at gmx.com
Tue Mar 8 06:48:14 PST 2011


On Tuesday 08 March 2011 04:54:45 spir wrote:
> 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.

??? It's for stuff that has to be defined at runtime. There's plenty of stuff that 
_has_ to be done at runtime and could _never_ be done at compile time no matter 
how great the language is. For instance, what if you want to have a variable 
with the time that the program started running? You certainly couldn't do that 
at compile time. Sure, there are things that you'd ideally be able to set with 
CTFE and currenly can't, but it's not like a better CTFE would negate the need 
for static constructors.

And honestly, in other cases, such as when you have to use a module constructor 
because of interdependencies between variables when initializing them and 
they're mutable, the fact that you can't do that at compile time is _fantastic_. 
In other programming languages, you run into problems because of the order of 
evaluation of the declarations of such variables. D makes them it so the order 
truly doesn't matter, because when it does, you have to use a module 
constructor. That's _huge_.

I really don't understand your problem with module constructors. They're 
fantastic.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list