Type constraint

Salih Dincer salihdb at hotmail.com
Mon Oct 9 15:56:47 UTC 2023


On Sunday, 8 October 2023 at 10:09:02 UTC, IchorDev wrote:
> On Wednesday, 4 October 2023 at 01:46:42 UTC, Joel wrote:
>> I think the if without static is still static, since it's part 
>> of the function name part, or so (outside of the curly bracket 
>> scope).
>
> You can't have regular if-statements inside templates. Regular 
> if-statements are checked at runtime but templates only exist 
> at compile-time.
>
> The way to write a *template constraint*—which is what you 
> want, and uses the `if` keyword—is thus:
>
> ```d
> struct List(T)
> if(__traits(isIntegral, T)){
>   auto addUp()
>     //(Add numbers)
>   }
> }
> ```
> Notice that the curly brace for the template comes after the 
> template constraint, and that there are only 2 curly braces 
> rather than the 3 from your example.

This snippet does not compile.  The curly brackets must be an 
even number, that is, they must terminate each other.

SDB at 79


More information about the Digitalmars-d-learn mailing list