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.

I assumed ElementType would not work, because static arrays don't satisfy 'isInputRange', and the documentation for ElementType says:

The element type is determined as the type yielded by r.front for an object r of type R. [...] If R doesn't have front, ElementType!R is void.

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.

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.)

--- Import std.range ---
@safe unittest
{
    import std.range;

    ubyte[10] staticArray;
    ubyte[] dynamicArray = new ubyte[](10);

    static assert(is(ElementType!(typeof(staticArray)) == ubyte));
static assert(is(ElementType!(typeof(dynamicArray)) == ubyte));

    // front is available
    static assert(__traits(compiles, staticArray.front));
    static assert(__traits(compiles, dynamicArray.front));

    static assert(is(typeof(staticArray.front) == ubyte));
    static assert(is(typeof(dynamicArray.front) == ubyte));
}

--- Import std.range.ElementType ---
@safe unittest
{
    import std.range : ElementType;

    ubyte[10] staticArray;
    ubyte[] dynamicArray = new ubyte[](10);

    static assert(is(ElementType!(typeof(staticArray)) == ubyte));
static assert(is(ElementType!(typeof(dynamicArray)) == ubyte));

    // front is not available
    static assert(!__traits(compiles, staticArray.front));
    static assert(!__traits(compiles, dynamicArray.front));

    static assert(!is(typeof(staticArray.front) == ubyte));
    static assert(!is(typeof(dynamicArray.front) == ubyte));
}

This suggests the documentation for ElementType not quite correct.

Reply via email to