Can someone explain this error?

Sergey Gromov snake.scaly at gmail.com
Thu Sep 25 05:33:32 PDT 2008


In article <gbbtue$1uam$1 at digitalmars.com>, sean at invisibleduck.org 
says...
>     class C
>     {
>         this() {}
>         this( int x, int y ) {}
>     }
> 
>     void main()
>     {
>         auto c = alloc!(C);
>         auto d = alloc!(C)( 1, 2 );
>     }
> 
>     T alloc(T, Params ...)( Params params )
>     {
>         return new T( params );
>     }
> 
> $ dmd test
> test.d(10): Error: expected 0 arguments, not 2

I dug this case a bit more in 2.019.  First of all, it's possible to 
make it work for non-zero argument count by making a single change in 
the template body:

    T alloc(T, Params ...)( Params params )
    {
        cast(void) params;
        return new T( params );
    }

though it stops accepting zero arguments because "tuple has no effect in 
expression (tuple())".  The weirdest part is when you try to access 
number of arguments in the tuple:

    void main()
    {
        auto d = alloc!(C)( 1, 2 );
    }

    T alloc(T, Params ...)( Params params )
    {
        cast(void) params;
        pragma( msg, Params.length.stringof );
        return new T( params );
    }

when compiling, prints:

    0u
    2u

but without the cast:

    0u
    test.d(12): Error: expected 0 arguments, not 2

So it instantiates the template once, check whether the tuple argument 
is explicitly used inside the template body, then instantiates it again 
with number of arguments depending on the previous instantiation.  Looks 
to me like a dirty hack in the compiler.


More information about the Digitalmars-d-learn mailing list