digitalmars.D - type of array element, type of assoz key?
- dennis luehring (8/8) Aug 04 2007 how can i get the element type of an array at compiletime?
- Frits van Bommel (44/54) Aug 05 2007 (This sort of post is more appropriate in digitalmars.D.learn, followups...
- Christian Kamm (17/18) Aug 05 2007 For dynamic arrays and associative arrays, something like this would wor...
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
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
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