Reputation: 2254
C++11 introduced a feature called 'extern template' which indicates that template instance exists in other translate unit.(Am I right?)
This(http://www.youtube.com/watch?v=3annCCTx35o) lecture also tells that if you specify extern template and don't include instantiation, the linker will produce error.(around 2:25 in the video)
So, I've tried to build next code:
#include <iostream>
template<class T>
struct Foo
{
static constexpr int type_size = sizeof(T);
};
extern template struct Foo<int>;
int main()
{
std::cout<< Foo<int>::type_size << std::endl;
return 0;
}
I expected the build will fail because this file does not contain explicit instantiation nor specialization, but gcc just builds it up the result runs well.
What am I missing? Or, am I misunderstanding something? Or, does not gcc support extern template well?
I've tried a class with non-inline function, and extern template works as expected!
#include <iostream>
template<class T>
struct Foo
{
static void print(T t);
};
template<class T>
void Foo<T>::print(T t) { std::cout << t << std::endl; }
extern template struct Foo<int>;
// template struct Foo<int>;
int main()
{
Foo<int>::print(1);
return 0;
}
Above source is not built without the commented line. Thank you all guys!
Upvotes: 2
Views: 1323
Reputation:
if you specify extern template and don't include instantiation, the linker will produce error.
No, not necessarily. There is only a problem if you actually use the template. You're using a compile-time constant defined as a static member of that template, but that is replaced by the constant's value at compile-time. And after that replacement, there is no longer any use of the template, so there is no need for a definition of the template.
Upvotes: 3