Template instantiation and overloaded functions

Falk-Florian Henrich schreibmalwieder at hammerfort.de
Mon Mar 26 01:37:47 PDT 2007


Am Mon, 26 Mar 2007 08:27:03 +1000 schrieb Daniel Keep:

> Falk Henrich wrote:
>> I'm troubled by D's template instantiation algorithm in combination
>> with overloaded functions. If I have
>> ...
> I think what's happening here is that when you specify &plus, since it's
> overloaded, it takes the first one it finds.  It then grabs a and b, and
> then tries to instantiate the template.

I think the compiler should be able to handle this situation (although 
the D spec doesn't answer this question). Its type inference algorithm is 
just too weak. Certainly, doing more type inference would make the 
compiler slower, but it eases the programmer's life a lot.

> One solution is to put your operator functions in a template, and always
> access them explicitly, like so:
> 
>> T plus(T)(T a, T b) { return a + b; }
>>
>> zip(&plus!(int), a, b);

I know, but that's ugly.

> Another solution, which is a bit more hacky, would be to overload the
> zip function with a second version that looks like this:
> 
>> tZipResult!(fn, X, Y)[] zip(alias fn, X, Y)(X[] a, Y[] b) {
>>     // ...
>> }
> 
> And use that casting trick I mentioned earlier to derive the 'Z' type,
> and get the function overload you actually want.  So to the user, it
> would look like this:
> 
>> zip!(plus)(a, b);

Maybe I will try to figure that out...

> Incidentally, I never wrote a 'zip' function because you can't return
> tuples from functions yet[1]. :P  Yours looks more like two-argument
> map... n-argument map should be possible using variadic templates (so
> long as the collection types aren't iterators, in which case you're
> screwed), I just never got around to doing it. :P

Of course, it's a matter of definition. I'm just reimplementing this one:

http://uebb.cs.tu-berlin.de/~opal/ocs/doc/html/BibOpalicaManual/
SeqZip.html#IDX2882

> In any case, a few people have suggested a number of times that it be
> possible to pick out one particular instance of an overload, but no nice
> way of doing it has actually emerged.  :(

As I mentioned above, I think the root of all these problems

- deduce the correct overload of a function
- infer arguments to a delegate / function literal
- ...

seems to be a weak type inference algorithm. It will get worse with every 
advanced feature that is introduced to the language (i.e., AST 
macros, ...). In my opinion, introducing killer features doesn't help if 
one has to apply subtle tricks to get things to work. And D runs the risk 
of becoming an awkward potpourri of features like C++.

Don't get me wrong, I really appreciate that D includes a number of major 
improvements compared to C/C++/C#/Java (which makes learning D worthwhile 
even if one uses templates only in a restricted manner).

Falk


More information about the Digitalmars-d-learn mailing list