Consider the following code:
#include <iostream>
template<typename T>
class X
{
public:
T t;
void func1() { std::cout << "Test"; }
void func2(T x) { }
};
extern template class X<int>;
int main()
{
X<int> x;
x.func1();
}
This code compiles and links correctly (live).
However, I cannot understand why I don't get a link error due to the extern template class
declaration. According to cppreference.com (emphasis mine):
An explicit instantiation declaration (an extern template) skips implicit instantiation step: the code that would otherwise cause an implicit instantiation instead uses the explicit instantiation definition provided elsewhere (resulting in link errors if no such instantiation exists). This can be used to reduce compilation times by explicitly declaring a template instantiation in all but one of the source files using it, and explicitly defining it in the remaining file.
As far as I understand, the extern template class
declaration should prevent the compiler from implicitly instantiating X with T = int
in main
. Because no instantiation actually exists, this should result in link-time errors.
Why does this code link?
Aucun commentaire:
Enregistrer un commentaire