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

Elmar chrehme at gmx.de
Sun Oct 10 13:01:46 UTC 2021


Hey D people.

Currently in my project I have worked on a unified type interface 
for all arrays which requires fixed-size arrays to be stored as 
pointer (in correspondence to dynamic and associative arrays) and 
allow them being allocated with any selected allocator.

There can be code like this:

```d
enum isPointedStaticArray(T) = (is(T : P*, P) && 
.isStaticArray!P);

//...
static if (.isPointedStaticArray!T)
{
     // ...
}
```

It won't compile when the argument of `isPointedStaticArray()` is 
NO pointer.

The compiler complains, about **`P` being undefined**.

What is the best workaround for this?
It's crazy. I can reverse the problem that it only fails if the 
argument IS a pointer:

```d
	enum isPointedStaticArray(T) =
	(){
		enum condition = `is(`~T.stringof~` : P*, P) && 
.isStaticArray!P`;
		static if (__traits(compiles, mixin(condition)) )
			return mixin(condition);  // "P already defined" error
		else
			return false;
	}();
```

Types defined in `__traits(compiles, ...)` are emitted to the 
outside?!

Okay, this is my current workaround:

```d
enum isPointedStaticArray(T) =
(){
	static if (is(T : P*, P))
		return .isStaticArray!(P);
	else
		return false;
}();

// ...
static if (isPointedStaticArray!T)
{

}
```

for outlining an expression `is(...) && ...`


Is there a simpler way in D to do this? If there only would be a 
`&&&` short circuit operator which doesn't compile the right side 
if the left side wouldn't compile to true.

Did someone already had the idea of a `static-try-catch` which 
catches compilation errors?


More information about the Digitalmars-d-learn mailing list