How to get element type of a slice?
Steven Schveighoffer
schveiguy at gmail.com
Tue Aug 17 13:14:44 UTC 2021
On 8/17/21 8:21 AM, Ferhat Kurtulmuş wrote:
> Hello folks,
>
> Hope everyone is doing fine. Considering the following code, in the
> first condition, I am extracting the type Point from the slice Point[].
> I searched in the std.traits, and could not find a neater solution
> something like ElementTypeOf!T. Is there any neater solution for it?
> Thanks in advance.
>
> ```d
> static if (isArray!VecPoint){
> VecPoint dummy;
> alias Point = typeof(dummy[0]);
> } else static if (isRandomAccessRange!VecPoint){
> alias ASeq2 = TemplateArgsOf!VecPoint;
> alias Point = ASeq2[0];
> } else
> static assert(0, typeof(VecPoint).stringof ~ " type is not
> supported");
> ```
If you want the element type of a range (i.e. the thing returned by
`range.front`), you can use `ElementType!T` (from std.range.primitives).
This returns the element type of the range, which for every array
*except* character arrays, gives you the element type of the array.
If you want always the element type of the array, even for auto-decoded
ranges, use `ElementEncodingType!T`.
If you know it's an array, you can just use Paul's solution.
Your `isRandomAccessRange` branch seems very suspect.
-Steve
More information about the Digitalmars-d-learn
mailing list