有没有办法预编译一些(类模板的)模板实例化但不是全部,以便在实例化时编译其余部分(在链接时没有错误)?
为了演示这个问题,考虑这个例子:
// 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
的 "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
中的预编译代码,编译器将找到另一个编译版本。
那么我怎样才能避免这两个问题呢?我认为一个相关的问题是“我如何指定一个预编译的头文件(仅)完全编译某些模板参数的模板?”
最佳答案
您可以使用 extern template
来防止给定 TU 中模板的特定实例化。
// 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
链接在一起,您的程序就可以运行。
关于c++ - 模板的选择性编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52186537/