使用extern模板(C ++ 11)
TemplHeader.h
template<typename T>void f();
TemplCpp.cpp
template<typename T>void f(){
//...} //explicit instantationtemplate void f<T>();Main.cpp的
#include "TemplHeader.h"extern template void f<T>(); //is this correct?int main() {
f<char>();
return 0;}这是正确的使用方法extern template,还是仅将此关键字用于类模板,如图2所示?
TemplHeader.h
template<typename T>class foo {
T f();};TemplCpp.cpp
template<typename T>void foo<T>::f() {
//...}//explicit instantationtemplate class foo<int>;Main.cpp的
#include "TemplHeader.h"extern template class foo<int>();int main() {
foo<int> test;
return 0;}我知道将所有这些放在一个头文件中是好的,但如果我们在多个文件中实例化具有相同参数的模板,那么我们会得到多个相同的定义,编译器会将它们全部删除(除了一个)以避免错误。我该怎么用extern template?我们可以只将它用于类,还是可以将它用于函数?
此外,图1和图2可以扩展为模板位于单个头文件中的解决方案。在这种情况下,我们需要使用extern template关键字来避免多个相同的瞬时。这仅适用于课程或功能吗?
12345678_0001
陪伴而非守候
相关分类