// CPP file
template<typename T>
void foo()
{
}
// Use the template only in this CPP as foo<int>, foo<char>, etc.
Suppose I have CPP file and there I have a template function foo for internal usage inside this CPP file only. Do I understand right that if I don't put the template into anonymous namespace or don't make it static, its instantiations used/created in this CPP file (e.g. foo<int>{}, foo<char>{}, etc.) will have external linkage, i.e. will be seen outside. So is it true, that I better have the template static, as shown below or have it in anonymous namespace?
// CPP file
template<typename T>
static void foo()
{
}
The whole function template has external linkage by default. Specializations/instantiations do not have any separate linkage attribute. Since foo is however a template it is however allowed to have multiple definitions in multiple translation units nonetheless, but only as long as they are exactly identical.
If you don't give it internal linkage explicitly and another translation unit happens to define another function template of the signature and name
template<typename T>
void foo();
with a different definition, then your program will violate the one-definition rule and have undefined behavior.
So yes, it must be declared static or in an anonymous namespace, if that is (possibly) going to be the case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With