A Huge Bummer When Using alias this

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Thu Mar 24 17:12:59 PDT 2016


On Thu, Mar 24, 2016 at 11:04:32PM +0000, ZombineDev via Digitalmars-d wrote:
> On Thursday, 24 March 2016 at 21:26:00 UTC, Jack Stouffer wrote:
> >alias this is only useful when not using any function that relies on the
> >template constraints in std.traits.
> >
> >For example
> >
> >import std.traits;
> >
> >void someFunc(N)(N val) if (isNumeric!N)
> >{
> >    int b = val;
> >}
> >
> >void main()
> >{
> >    import std.typecons;
> >    Nullable!int a = 42;
> >
> >    someFunc(a);
> >}
> >
> >$ dmd test.d
> >test.d(13): Error: template someFunc cannot deduce function from argument
> >types !()(Nullable!(int))
> >
> >Removing the template constraint makes it compile and run just fine.
> >What's a good work around for these types of issues?
> 
> `isNumeric(T)` explicitly allows only built-in types (int, float,
> etc.) and prevents user-defined types.
> Use  `if (is(NumericTypeOf!T N))` if you want to allow types `T` that
> can convert to some numeric type `N`.
[...]

IMO, isNumeric is a misnomer.  It really should be named
isBuiltinNumeric or something along those lines. A "real" isNumeric
ought to test if the type supports arithmetic operations...

In this particular case, though, I'm not sure why you need to use
isNumeric, since you already know you want int to be the target type, so
you could just write:

	void someFunc(N)(N val) if (is(N : int)) ...

and it should work.


T

-- 
Let X be the set not defined by this sentence...


More information about the Digitalmars-d mailing list