How to get element type of a slice?

jfondren julian.fondren at gmail.com
Tue Aug 17 12:26:36 UTC 2021


On Tuesday, 17 August 2021 at 12:21:31 UTC, 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");
> ```
>
> Ferhat

This one's not in std.traits:

```d
import std.range : ElementType;

struct Point { int x, y; }

unittest {
     Point[] points;
     assert(is(ElementType!(typeof(points)) == Point));
}
```


More information about the Digitalmars-d-learn mailing list