// file.h template<typename T> class object { /* lots of code */ }; // file.inc template<typename T> object::object(const T*data) { /* ... */ } // and more: definitions of all non-inline functionality of class object<> // file.cc to be compiled and linked #include "file.h" #include "file.inc" template struct<int>; template struct<double>; // user.cc #include "user.h" #include "file.h" object<double> x{0.4} // okay: uses pre-compiled code object<user_defined> z(user_defined{"file.dat"}); // error: fails at linking
如果用户 #include s码 "file.inc"
#include
"file.inc"
// user.cc #include "user.h" #include "file.h" #include "file.inc" object<double> x{0.4} // error: duplicate code object<user_defined> z(user_defined{"file.dat"}); // okay
file.cc .
file.cc
你可以用 extern template 防止在给定的TU中实例化模板。
extern template
// src0.cpp template class foo<int>; // Oblige instantiation of `foo<int>` in this TU
// src1.cpp extern template class foo<int>; // Prevent instantiation of `foo<int>` in this TU
src0 和 src1 连接在一起,你的程序就可以运行了。
src0
src1