What is the proper way to outline static-if-conditions ?

Elmar chrehme at gmx.de
Sun Oct 10 15:01:17 UTC 2021


On Sunday, 10 October 2021 at 14:36:50 UTC, Elmar wrote:
> On Sunday, 10 October 2021 at 14:08:13 UTC, drug wrote:
>> You just need to check if T is a pointer:
>> ```D
>> import std;
>>
>> alias DA = int[];
>> alias SA = int[3];
>>
>> alias PSA = SA*;
>> alias PDA = DA*;
>>
>> version(all)
>> 	enum isPointedStaticArray(T) = isPointer!T && 
>> isStaticArray!(PointerTarget!T);
>> else
>> 	enum isPointedStaticArray(T) = isPointer!T && 
>> is(PointerTarget!T : P[N], P, size_t N);  // this way you can 
>> get array length
>>
>> static assert(!isPointedStaticArray!DA);
>> static assert(!isPointedStaticArray!SA);
>> static assert(!isPointedStaticArray!PDA);
>> static assert( isPointedStaticArray!PSA);
>>
>> void main()
>> {
>> }
>> ```
>> https://run.dlang.io/is/qKdx1D
>>
>> Also you can use another way to detect static array - it can 
>> be useful if you need to get its length
>
> Wow, this is a fine solution. I gonna use it, thank you :-) .

Well, I just wondered why your code would compile and mine 
wouldn't. The `version(all)` variant will not compile on my 
computer with `rdmd` because `PointerTarget` only allows pointers.

But the 2nd one will compile. The `is()` expression catches the 
compilation error which is nice. This is sufficient:

```d
enum isPointedStaticArray(T) = is(PointerTarget!T : P[N], P, 
size_t N);
```

It would be nice if one could use pattern-matching for it in D. 
Is this possible?

```d
	enum isPointedStaticArray(X : P*, P) = 
.isStaticArray!(PointerTarget!X);
	enum isPointedStaticArray(X : else) = false;
```



More information about the Digitalmars-d-learn mailing list