显式实例化源文件中的定义时,header 中是否需要显式模板实例化声明?

Are explicit template instantiation declarations required in the header when explicitly instantiating the definitions in the source file?

中,已接受的答案涉及 header 文件中的模板函数 声明,该文件具有 定义 在源文件中。为了使此模板函数也可用于其他翻译单元,在源文件中为每个 "allowed" 用法进行了显式模板实例化。到目前为止,这在我看来是标准做法。

不过,答案还建议在 header 文件中放置相应的显式模板实例 declarations。我以前没有见过这种做法,想知道这是否是标准所要求的。

这是一个小例子:

A.h

struct A
{
    template<class T>
    void g(T t);
};

A.cpp

#include "A.h"

template<class T>
void A::g(T t)
{ /* ... */ }

template void A::g(int); // Explicit instantiation of the definition.

main.cpp

#include "A.h"

int main()
{
    A a;
    a.g(0);
}

wording in the standard 没有让我清楚是否还需要 声明 的显式实例化。这似乎主要涉及 "the definition is never instantiated explicitly, an implicit instantiation in A.cpp is not guaranteed to be retained" 案例(未描述),但我希望得到澄清。

Are explicit template instantiation declarations required in the header when explicitly instantiating the definitions in the source file?

没有。规则是,来自[temp]/10,强调我的:

A function template, member function of a class template, variable template, or static data member of a class template shall be defined in every translation unit in which it is implicitly instantiated unless the corresponding specialization is explicitly instantiated in some translation unit; no diagnostic is required.

在您的示例中,A::g<int>main.cpp 中隐式实例化,但在 "some translation unit" (A.cpp) 中显式实例化。程序没问题。