Can I make a template of this in D somehow?

78 Views Asked by At

This does not work (this is inside a class):

template this(T : U[], U)
    {
        this (U[] array)
        {
            static if (is(U:V[],V)  // array
            {


            } 
            else static if (is(U:V[string]),V) // hash
            {

            }
            
        }
    }

Is there a way around to get it work?

1

There are 1 best solutions below

0
Steven Schveighoffer On

You can't define a template constructor long-form (the template identifier cannot be a keyword according to the grammar). You can do it like this:

this(U)(U[] array) {
   // same stuff
}

Note that there is no valid way to explicitly instantiate such a ctor, it must use IFTI.

This case doesn't seem to need it, but if you do need more control over the template instantiation, you can use a factory function.