How to get the element type of an array?
Steven Schveighoffer
schveiguy at gmail.com
Tue Aug 25 12:50:35 UTC 2020
On 8/25/20 4:38 AM, Jon Degenhardt wrote:
> On Tuesday, 25 August 2020 at 05:02:46 UTC, Basile B. wrote:
>> On Tuesday, 25 August 2020 at 03:41:06 UTC, Jon Degenhardt wrote:
>>> What's the best way to get the element type of an array at compile time?
>>>
>>> Something like std.range.ElementType except that works on any array
>>> type. There is std.traits.ForeachType, but it wasn't clear if that
>>> was the right thing.
>>>
>>> --Jon
>>
>> I'm curious to know what are the array types that were not accepted by
>> ElementType ( or ElementEncodingType ) ?
>
> Interesting. I need to test static arrays. In fact 'ElementType' does
> work with static arrays. Which is likely what you expected.
Also note that due to autodecoding, ElementType says `dchar` for
strings. ElementEncodingType should be the choice if you are looking for
the array element type. But you could also use the techniques specified
here (and might be less confusing).
> But, if std.range is imported, a static array does indeed get a 'front'
> member. It doesn't satisfy isInputRange, but it does have a 'front'
> element.
Because you can't pop the front of a static array. front works because a
static array automatically casts to a normal array (there is no
specialized overload for static arrays).
> The situation is still confusing though. If only 'std.range.ElementType'
> is imported, a static array does not have a 'front' member, but
> ElementType still gets the correct type. (This is where the
> documentation says it'll return void.)
You are maybe thinking of how C works? D imports are different, the code
is defined the same no matter how it is imported. *your* module cannot
see std.range.primitives.front, but the range module itself can see that
UFCS function.
This is also why ElementType will fail on types that have UFCS front
defined, but not imported directly from std.range.primitives.
-Steve
More information about the Digitalmars-d-learn
mailing list