Are templated functions always re-constructed?

H. S. Teoh hsteoh at
Tue Nov 16 21:30:08 UTC 2021

On Tue, Nov 16, 2021 at 09:14:50PM +0000, rempas via Digitalmars-d-learn wrote:
> Let's say that I have the following function:
> ```
> void add(T)(T val, T val2) { return val + val2; } // Classic example, lol
> ```
> Now let's say that I call the function passing an `int` parameter. The
> function will get built with an `int` type. What happens the second
> time that I will call it again? Will it get the already build function
> or will it make a new one? I suppose it re-uses it but still I wanted
> to ask just in case. Please only answer if you are sure and not be
> making guesses because it is really important! Thanks!

Short answer: a template called with the same CT arguments will only be
instantiated once, and reused thereafter.

Long answer: the above applies per compilation. If you compile your
sources separately, there may be multiple instantiations of the template
with the same CT arguments.  However, unless something went wrong, these
duplicates will be dropped by the linker.


Making non-nullable pointers is just plugging one hole in a cheese grater. -- Walter Bright

More information about the Digitalmars-d-learn mailing list