C++ 模板函数自动静态? (不,他们不是)

C++ template functions are automatically static? (No, they aren't)

当你写一个模板函数(或成员)时,你必须在头文件中写主体。这是非常有意义的,因为模板本质上是对编译器的指令,说明如何根据初始化前未知的类型动态创建函数。

我的问题与一个定义规则有关,如果我用相同类型初始化模板(例如 typename T 变为 int) 在两个不同的文件中,我 link 他们在一起我没有多重定义错误。

这是什么原因?模板函数是否隐式 static 因此在其编译单元之外不可见?

还是另有原因?

回答: 不,他们不是。它们是一个定义规则的例外。

该标准在模板的单一定义规则中包含一个特殊例外。

N4140,强调我的:

3.2 One definition rule [basic.def.odr]

6 There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. [...]

以下要求有效地说明所有定义都必须相同,但我假设它们在您的代码中。

你可以看出模板函数既不是隐式 inline 也不是隐式 static,因为这个程序可以工作:

a.cc:

template <typename T> T f();
int main() { return f<int>(); }

b.cc:

template <typename T> T f() { return T(); }
template int f();

如果模板是隐式的 inline,则此程序将无效,因为必须在使用它的每个翻译单元中定义 inline 函数。

如果模板是隐式的 static,则此程序将无效,因为 b.cc 中的定义将无法与 a.cc 中的声明相匹配。