Can anyone provide an example of how D templates are overridable by global symbols?
kinke
noone at nowhere.com
Thu Jan 27 21:50:12 UTC 2022
An example:
a.d:
```
import core.stdc.stdio;
void foo()() {
version (Oops)
printf(" foo - oops\n");
else
printf(" foo\n");
}
void doA() {
printf("doA:\n");
foo!();
}
```
b.d:
```
import core.stdc.stdio;
import a;
void main() {
printf("main:\n");
foo!();
doA();
}
```
```bash
$ dmd -c a.d -version=Oops
$ dmd -c b.d
$ dmd a.o b.o -of=ab
$ ./ab
main:
foo - oops
doA:
foo - oops
$ dmd b.o a.o -of=ba
$ ./ba
main:
foo
doA:
foo
```
Each object file contains a foo!() instantiation (in a.o, the
Oops version). No inlining, so the linker takes one of the weak
definitions, and we end up with a consistent behavior for both
calls - but the picked version is determined by the order of the
object files.
Now if the calls are inlined, the behavior might not be
consistent anymore. So separate compilations with different
compiler flags can cause observable differences.
More information about the Digitalmars-d-learn
mailing list