www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - using enums as key in associative array

Content-Type: text/plain; charset=UTF-8


I'm a beginner in D; I have just begun the book from Andrei.

I would like to know how to statically declare an associative array whose
key are enums.

example :

import std.stdio, std.string;

enum deviceType {cpu, gpu}
auto execDeviceSuffix = [deviceType.cpu:".cpu", deviceType.gpu:".gpu"];

void main(){
  foreach(deviceSuffix; execDeviceSuffix.values) writeln(deviceSuffix);

This won't compile and give the error:
Error: non-constant expression

I have two questions :
1) Why are there casts in the error message ?
Are the enums always substituted by with their base type ?

2) where is the non constant part in this expression ?
Both the deviceType enum and the strings are constant.

Thank you for your help !

Wilfried Kirschenmann

"An expert is a person who has made all the mistakes that can be made in a
very narrow field."*
*Niels Bohr - *Danish physicist (1885 - 1962)*

Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

Hi,<div><br></div><div>I&#39;m a=C2=A0beginner=C2=A0in D; I have just begun=
 the book from Andrei.</div><div><br></div><div>I would like to know how to=
=C2=A0statically=C2=A0declare an associative array whose key are enums.</di=

<div>example :=C2=A0</div><div><div>#!../dmd2/linux/bin/rdmd</div><div><br>=
</div><div>import std.stdio, std.string;</div><div><br></div><div>enum devi=
ceType {cpu, gpu}</div></div><div>auto execDeviceSuffix =3D [deviceType.cpu=
:&quot;.cpu&quot;, deviceType.gpu:&quot;.gpu&quot;];</div>

<div><br></div><div>void main(){</div><div>=C2=A0=C2=A0foreach(deviceSuffix=
;=C2=A0execDeviceSuffix.values) writeln(deviceSuffix);</div><div>}</div><di=
v><br></div><div><br></div><div>This won&#39;t compile and give the error:<=
Error: non-constant expression [cast(deviceType)0:&quot;.cpu&quot;,cast(dev=
<div><br></div><div>I have two questions :=C2=A0</div><div>1) Why are there=
 casts in the error message ?</div><div>Are the enums always substituted by=
 with their base type ?</div><div><br></div><div>2) where is the non consta=
nt part in this expression ?</div>

<div>Both the=C2=A0deviceType=C2=A0enum and the strings are constant.</div>=
<div><br></div><div>Thank you for your help !</div><div><br></div><div>----=
-<br>Cordialement,<br>Wilfried Kirschenmann<br><br>&quot;An expert is a per=
son who has made all the mistakes that can be made in a very narrow field.&=

</b>Niels Bohr - <i>Danish physicist (1885 - 1962)</i><br>

Mar 07 2011