Poll: what should this program do?

Timon Gehr timon.gehr at gmx.ch
Thu Mar 20 22:33:29 UTC 2025


On 3/19/25 04:40, Paul Backus wrote:
> Here's a weird little program that came up in a recent Discord discussion:
> 
>      template fun(T)
>      {
>          string fun(T) => fun("hi");
>          string fun(string) => "inner";
>      }
>      string fun(string) => "outer";
> 
>      void main()
>      {
>          import std.stdio;
>          writeln(fun(123));
>      }
> 
> 
> **What SHOULD this program do?**
> 
> 1. Print "inner".
> 2. Print "outer".
> 3. It shouldn't compile.
> ...

According to the documentation, IFTI wouldn't really apply at all 
because the first declaration is not a function template. Of course, 
what happens in practice is different. (But with the same result here.)


> **What do you think it ACTUALLY does?**
> 
> 1. Print "inner".
> 2. Print "outer".
> 3. It doesn't compile.

Maybe "stack overflow' should have been one of the options ;).

It prints "outer", because IFTI is considered a worse match due to `T` 
being deduced. I don't think this behavior is documented. (But if you do 
`template foo()` and replace `T` with `string` in the body, you will get 
an ambiguity error.)

This is another fun case:

```d
template fun(T)
{
     string fun(string) => "first";
     string fun(const(T)) => fun("second");
}
pragma(msg, fun("123"));
```

```d
template fun(T=string)
{
	string fun(string) => "first";
	string fun(const(T)) => "second";
}
pragma(msg, fun("123"));
```


More information about the Digitalmars-d mailing list