Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local function template in cpp file: should I make it static?

// 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()
{
}
like image 742
JenyaKh Avatar asked Jun 25 '26 09:06

JenyaKh


1 Answers

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.

like image 133
user17732522 Avatar answered Jun 28 '26 00:06

user17732522