www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - type of array element, type of assoz key?

reply dennis luehring <dl.soluz gmx.net> writes:
how can i get the element type of an array at compiletime?

example:
   int test[5] --> int
   double test[] --> double

and what is the type of the key of an assoz. array?

   int test[char[]] --> int, char[]
   double test[int] --> double, int

thx
Aug 04 2007
next sibling parent Frits van Bommel <fvbommel REMwOVExCAPSs.nl> writes:
dennis luehring wrote:
 how can i get the element type of an array at compiletime?
 
 example:
   int test[5] --> int
   double test[] --> double
 
 and what is the type of the key of an assoz. array?
 
   int test[char[]] --> int, char[]
   double test[int] --> double, int

(This sort of post is more appropriate in digitalmars.D.learn, followups set) typeof to the rescue: ----- import std.stdio; void main() { // (typeid is just wrapped around the types to make them printable) // Element type of regular arrays: typeof(arr[0]); { int test[5]; writefln(typeid( typeof(test[0]) )); } writefln(); { double test[]; writefln(typeid( typeof(test[0]) )); } writefln(); // Assoc. arrays: // key type == typeof(arr.keys[0]) // value type == typeof(arr.values[0]) { int test[char[]]; writefln(typeid( typeof(test.values[0]) )); writefln(typeid( typeof(test.keys[0]) )); } writefln(); { double test[int]; writefln(typeid( typeof(test.values[0]) )); writefln(typeid( typeof(test.keys[0]) )); } } ----- output: ===== int double int char[] double int =====
Aug 05 2007
prev sibling parent Christian Kamm <kamm.incasoftware shift-at-left-and-remove-this.de> writes:
dennis luehring wrote:

 how can i get the element type of an array at compiletime?

For dynamic arrays and associative arrays, something like this would work: template ArrayElementType(T : T[]) { alias T ArrayElementType; } template AATypes(T) { // todo: static assert if T is no AA type here alias ArrayElementType!(typeof(T.keys)) key; alias ArrayElementType!(typeof(T.values)) value; } Thinking about it, it's probably simpler to just use typeof(array[0]) typeof(aa.keys[0]), typeof(aa.values[0]). Cheers, Christian
Aug 05 2007