Is it possible to do this with a template?

RazvanN razvan.nitu1305 at gmail.com
Fri Dec 17 16:02:45 UTC 2021


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?

There is also a compiler trait [1] which can do that for you:

```d
void main()
{
     int val = 10;
     static if (__traits(isSame, typeof(val), int)) {}
}
```


[1] https://dlang.org/spec/traits.html#isSame


More information about the Digitalmars-d-learn mailing list