Niko
Niko

Reputation: 26730

Should template functions be static?

I often declare utility functions in my source files as static to have them linked internally. Now I have a header file with lots of template functions (in a named namespace). Should I make them also static to avoid linking errors or do template functions behave differently?

Upvotes: 6

Views: 3824

Answers (1)

Ad N
Ad N

Reputation: 8386

Template functions are implicitly inline (note: not their explicit specialization(s)). So you will not have a linker error related to multiple definitions of the same function. Actually inline is now mainly perceived as a linker directive, preventing violations of the ODR.

 Rationale 

If you think about it, implicitly disabling ODR violations for function templates makes the most sense.

The compiler does not instantiate a function template when it sees its definition, it is instantiated when it is used: it is only when the function template is used that the compiler knows which arguments to substitute in the template parameters.

In order to be able to instantiate the function, the compiler needs to see the function template definition at the call site, so said definition is usually kept in the same header declaring the function template. Since this is such a common usage, implicitly marking function template as inline save you some typing !

static

Regarding the static keyword: when applied to a non-member function, it will give you internal linkage: the method will be available only in the compilation unit(s) where it is defined.

Following the usual approach to function template (providing the definition alongside the declaration in the header), making them static present little advantage: the function definition should be available in every translation unit that is seeing the function declaration.

Upvotes: 13

Related Questions