c++ - 模板的选择性编译

标签 c++ templates compilation

有没有办法预编译一些(类模板的)模板实例化但不是全部,以便在实例化时编译其余部分(在链接时没有错误)?

为了演示这个问题,考虑这个例子:

// 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

只要 src0src1 链接在一起,您的程序就可以运行。

关于c++ - 模板的选择性编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52186537/

相关文章:

c++ - 如何理解 C++ Concurrency in Action 中同一类的实例导致死锁问题?

c++ - friend 模板定义。何时何地包含 <T>?

java - 类测试的意外输出

java - 使用 Java 1.5 编译 thrift 生成的类时出错

c++ - 可以输入单词的计算器

c++ - 如何在 qi 符号表中使用 std::function

c++ - gSOAP - 修改 HTTP POST header

c++ - 为什么 SFINAE (enable_if) 从类定义内部工作而不是从外部工作

c++ - 模板使用中空 "<>"是什么意思?

linux - 对 linux/mac 的文件更改运行操作?