Extract base type of any array?
Steven Schveighoffer
schveiguy at gmail.com
Sun Sep 19 11:45:31 UTC 2021
On 9/19/21 12:20 AM, jfondren wrote:
> On Sunday, 19 September 2021 at 03:58:41 UTC, Kirill wrote:
>> How can I get the base type of any
>> (multidimensional/static/dynamic/associative) array?
>>
>> Example:
>> ```
>> void main() {
>> int[][] intArr;
>> double[4][] doubleArr;
>> string[string][] strArr;
>>
>> intArr.example; // T = int
>> doubleArr.example; // T = double
>> strArr.example; // T = string
>> }
>>
>> void example(T)(<...> data) {
>> // extract the base of data (inside func's body or in <...>)
>> // preferably, T must become data's base type
>> }
>> ```
>
> This almost works, but as `string` is an array type it needs some kind
> of rule to stop there:
>
> ```d
> unittest {
> int[] intArr;
> double[4][] doubleArr;
> string[string][][] strArr;
>
> assert(is(BaseType!(typeof(intArr)) == int));
> assert(is(BaseType!(typeof(doubleArr)) == double));
> assert(is(BaseType!(typeof(strArr)) == immutable(char)));
> }
>
> template BaseType(T) {
> static if (__traits(isStaticArray, T))
> alias BaseType = BaseType!(typeof(T.init[0]));
> else static if (is(T == U[], U))
> alias BaseType = BaseType!U;
> else static if (is(T == V[K], K, V))
> alias BaseType = BaseType!V;
> else
> alias BaseType = T;
> }
> ```
>
> mix of BaseType!T from core.internal.array.equality and rank!T from
> Philippe Sigaud's D Templates Tutorial at
> https://github.com/PhilippeSigaud/D-templates-tutorial
You just need a case for it:
```d
static if(is(immutable(T) == immutable(string)))
alias BaseType = T;
else ... // everything else
```
-Steve
More information about the Digitalmars-d-learn
mailing list