Template parameter deduction for constructors?

Peter Alexander peter.alexander.au at gmail.com
Sun Apr 14 07:29:11 PDT 2013


On Saturday, 13 April 2013 at 15:52:01 UTC, David Nadlinger wrote:
> On Saturday, 13 April 2013 at 08:40:15 UTC, Peter Alexander 
> wrote:
>> This just seems like a bandaid solution to the problem. If it 
>> works in this case then beginners will think it works in every 
>> case, and will be even more confused when it stops working.
>
> When would it stop working? You might want to add any such 
> example to http://d.puremagic.com/issues/show_bug.cgi?id=6082.

Something like this:

struct Foo(T)
{
     static if (is(T == int))
         this(string x) {}
     else
         this(T x) {}
}

T is ambiguous for Foo("bar")


Also this:

struct Foo(T)
{
     this(T x) {}
     this(int x) {}
}

Calls to Foo(x) are ambiguous when is(typeof(x) : int).

Allowing deduction in this case would be frustrating. Imagine 
having a struct where this worked, and then you wanted to add a 
new constructor, or maybe just modify the constructor for one 
instantiation. You would then have to change all calls to 
explicitly specify parameters.


> The complexity is already there, in the form of (free) ITFI 
> functions.

Unfortunately you are right because of the eponymous template 
hack. Without it, normal functions are non-complex.

void foo(T)(T x) {}
void foo(string x) {}

Here, foo("bar") is unambiguously the second call. (D compilers 
don't allow template/non-template overloads at the moment due to 
a bug, but this should work).

Unfortunately the eponymous hack falls down quite easily. For 
example, IFTI on this function fails:

template foo(T)
{
     static if (true)
         void foo(T)(T x) {}
}

So it is just as fragile as this proposal.


More information about the Digitalmars-d mailing list