On Friday, 17 December 2021 at 07:52:18 UTC, rempas wrote:
I want to use an expression and put it in place inside the `if`
parentheses. The expression is: `is(typeof(val) == type)`. I
want to use a template called "is_same" that will take the
value and a type to place them to the respective places. I have
tried the following but it doesn't seem to work:
```
mixin template is_same(val, type) {
is(typeof(val) == type)
}
void main() {
int val = 10;
static if (is_same!(val, int)) {}
}
```
When trying to compile, I'm taking the following error message:
```
Error: declaration expected, not `is`
```
Is this a limitation of templates in D or is there a way to
bypass this?
It isn't really about limitation of templates. You're trying to
use mixin template and it's main purpose is to inject
declarations. If you want to replace `is expression` with
template you could use something like this:
```d
bool is_same(alias value, T)() {
return is(typeof(value) == T);
}
void main() {
int value = 10;
static if (is_same!(value, int)) {
writeln("it is true!");
} else {
writeln("it is false!");
}
}
```
Personally, I don't see any benefit with replacing that kind of
`is expressions` with templates. Perhaps I'm missing something :)