How to get element type of a slice?
Ferhat Kurtulmuş
aferust at gmail.com
Tue Aug 17 14:40:20 UTC 2021
On Tuesday, 17 August 2021 at 13:14:44 UTC, Steven Schveighoffer
wrote:
> 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
Very informative, thanks. My code is lying here[1]. I want my
struct to accept 2d static arrays, random access ranges, and
"std.container.Array". I could achieve it with its present form,
and I will probably slightly modify it based on your comments.
[1]:
https://github.com/aferust/earcut-d/blob/master/source/earcutd.d#L34
More information about the Digitalmars-d-learn
mailing list