是否有方法预编译某些模板实例化(类模板),但不是全部,以便在实例化时编译其余的模板(链接时出现w/o错误)?
为了演示这个问题,请考虑下面的示例:
// 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的预编译代码,编译器将找到另一个编译版本。
那么,我如何避免这两个问题呢?我认为一个相关的问题是:“如何指定预编译的头完全编译特定模板参数的模板(仅)?”
发布于 2018-09-05 13:40:41
您可以使用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连接在一起,你的程序就能工作。
https://stackoverflow.com/questions/52186537
复制相似问题