From Ada 2012

Artur Skawina art.08.09 at gmail.com
Thu May 3 08:58:46 PDT 2012


On 05/03/12 16:04, bearophile wrote:
> [p.19] >Arrays can be indexed by any discrete types (integers, enumeration)<
> 
> This is quite handy for enums (and sometimes chars), and reliable. Currently in D if you define an array with enum index you get an associative array, that is wasteful in both memory and performance for most enums that have contiguous values (but I think maybe D implementations will be free to use a more efficient array here, because the interface of AAs is opaque).

It's a reasonable default; D will let you choose how it's done.

   struct EA(T,I) {
      enum size_t FIRST = I.min, N = I.max - FIRST + 1;
      T[N] a;
      auto opIndex(I i) { return a[i-FIRST]; }
      auto opIndexAssign(T v, I i) { return a[i-FIRST] = v; }
      // etc for any other useful operator
   }

   enum E { one=10, two, three }

   EA!(int, E) a;
   a[E.three] = 42;
   assert(a[E.three]==42);
   assert(a.sizeof==int.sizeof*3);  

It doesn't get much more efficient than this; the compiler will take
care of the rest, both the type checking and optimizing it all away.

Maybe something like this should be in the std lib, but i'm not sure if
it's very useful in it's raw form, usually you'll want a custom version;
it would be more suited for a mixin-template library.

artur


More information about the Digitalmars-d mailing list