Template constraints should introduce identifiers inside their scopes
Timon Gehr
timon.gehr at gmx.ch
Thu Sep 22 16:52:54 UTC 2022
On 21.09.22 14:32, Paul Backus wrote:
>>
>> They are not semantically the same. The first can be instantiated with
>> any type and conditionally makes an output (it is empty otherwise),
>> the other says it cannot be instantiated unless the arguments have
>> specific properties.
>
> If you want the semantics to match exactly you can replace the `static
> if` with a `static assert` (or add `else static assert(0);`).
I think this is not true.
```d
module a;
template foo(T){
static assert(is(T==int));
}
template bar(T)if(is(T==int)){}
```
```d
module b;
template foo(T)if(is(T==float)){}
template bar(T)if(is(T==float)){}
```
```d
module c;
import a,b;
alias foo1=foo!int; // ok
alias foo2=foo!float; // error
alias bar1=bar!int; // ok
alias bar2=bar!float; // ok
```
`static assert` can give you a custom error message, but template
constraints have much better overloading behavior. The two features are
not comparable. Ideally template constraints would be improved so they
are a strictly better choice than static assert whenever they are
appropriate.
More information about the Digitalmars-d
mailing list