Type constraint

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Oct 3 17:42:51 UTC 2023


On Tuesday, October 3, 2023 8:35:31 AM MDT Joel via Digitalmars-d-learn wrote:
> Oh, I found,
> ```d
> static if (isIntegral!T)
> ```
> seems to work.

Yeah. static if will compile in the code in that branch based on whether the
condition is true, whereas if without the static will branch at runtime,
with both branches being compiled in. So, if you want to be changing what
code is being compiled in, you need static if, not if.

if(isIntegral!T)

will compile just fine, but it'll just end up being either

if(true)

or

if(false)

and the code within that branch will be compiled in regardless (and
potentially result in compiler errors if it doesn't work with the type that
that the template is being instantiated with). So, you usually want to use
static if with compile-time tests and not if.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list