do free template functions need to be static and inlined?

Viewed 90

Given this code

// In header file
template<typename T>
inline static void my_func(T var)
{
    std::cout << var << std::endl;
}

// Used in many cpp files:
void some_function()
{
    my_func(1);
    my_func("test");
}

I just "upgraded" my free function to a template. It was static and inlined before. But now its a template, I am not 100% if inline and static still apply - my guess is they do... but I am not 100% about the template generation mechanics (i.e. does it copy/paste it into each translation unit?)

1 Answers

All function templates are inline by default, so that keyword isn't needed.

The static keyword was likely unnecessary before you converted my_func to be a template, and likely still is. Marking a free function static gives its name internal linkage, but since it's declared in a header that doesn't accomplish much here. Any translation unit can simply #include your header and have access to the function anyway. static functions are much more useful in .cpp files, where it serves to essentially mark the function as internal and prevent other translation units from calling it.

Related