Can anyone provide an example of how D templates are overridable by global symbols?

Siarhei Siamashka siarhei.siamashka at gmail.com
Thu Jan 27 19:53:08 UTC 2022


On Thursday, 9 December 2021 at 21:06:54 UTC, Siarhei Siamashka 
wrote:
> On Thursday, 9 December 2021 at 20:53:52 UTC, Siarhei Siamashka 
> wrote:
>>   How would one construct a simple example of a template 
>> symbol getting successfully overridden by a global symbol?

Forgot to mention that a template function can be overridden by 
another function with the same name. But only as long as all of 
this happens in the scope of a single module. Here are a few 
examples (all of them successfully compile and run):

```D
import std.stdio;

T f(T)(T a, T b) { return a + b; }
int f(int a, int b) { return a - b; }

void main()
{
   f(2, 1).writeln; // prints "1"
}
```

```D
import std.stdio;

int f(int a, int b) { return a - b; }
T f(T)(T a, T b) { return a + b; }

void main()
{
   f(2, 1).writeln; // prints "1"
}
```

```D
import std.stdio;

import template_f;
int f(int a, int b) { return a - b; }

void main()
{
   f(2, 1).writeln; // prints "1"
}
```

```D
import std.stdio;

import nontemplate_f;
T f(T)(T a, T b) { return a + b; }

void main()
{
   f(2, 1).writeln; // prints "3"
}
```

This mostly agrees with the following part of the D language 
specification: https://dlang.org/spec/module.html#name_lookup

Except that having a template function and a non-template 
function with the same name within the same module scope doesn't 
seem to be explicitly documented in the D specification. But such 
name clash appears to be resolved in favor of a non-template 
function. And this behavior shouldn't inhibit functions inlining.


More information about the Digitalmars-d-learn mailing list