Template argument deduction and default args

anonymous via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 23 23:02:13 PDT 2014


On Thursday, 24 July 2014 at 04:53:41 UTC, Manu via Digitalmars-d
wrote:
> struct S(size_t len = 10)
> {
>   ubyte[len] data;
> }
>
> S!100 x; // this works fine
> S y; // this doesn't work (!)
> S!() z; // this works
>
> The template arg has a default arg, why require !() ??

So that the type S!() is (easily) distinguishable from the
template S.

> This causes problems in meta code, where you want to create an 
> instance of
> some T, and T may be a normal type with no template args, in 
> which case !()
> is invalid, but a template type with default args should also be
> acceptable, but it doesn't work because the meta code doesn't 
> specify !().

Add !() at the instantiation site.

> struct S(T)
> {
>   this(T t)
>   {
>     m = t;
>   }
>
>   T m;
> }
>
> int myThing;
> auto s = S(myThing); // error!
> auto s = S!(typeof(myThing))(myThing); // works, but horrible, 
> and breaks
> down again when used in place of non-template counterparts in 
> meta code.

Phobos goes with helper functions: S!T s(T)(T t) {return S!T(t);}
I'm not a fan either.


More information about the Digitalmars-d mailing list