Template Constraints

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Feb 24 03:58:48 UTC 2018


On Saturday, February 24, 2018 03:48:44 psychoticRabbit via Digitalmars-d-
learn wrote:
> On Saturday, 24 February 2018 at 03:43:25 UTC, Jonathan M Davis
>
> wrote:
> > That does not do what the OP requested at all. That tests
> > whether T is one of byte, ubyte, short, ushort, int, uint,
> > long, and ulong, whereas what the OP wants is to test whether T
> > can be cast to int.
> >
> > - Jonathan M Davis
>
> yeah. I realised that after I had posted.
>
> I posted a more suitable response after that though (I hope),
> with the intention of leading the OP away from an explicit cast,
> towards an implicit cast.

Whether an implicit cast or an explicit cast makes more sense depends
entirely on what the code is doing, but either way, the conversion needs to
be forced inside the function, or you end up with bugs. Far too often, when
someone has a template constraint that checks an implicit conversion, the
function doesn't actually force the conversion, and that can do anything
from resulting in some instantiations not compiling to causing subtle bugs
due to the argument being used without being converted. In general, it's
actually best to avoid conversions entirely with generic code and force the
caller to do the conversion if a conversion is appropriate.

But ultimately, what works best depends on what the code is trying to do.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list