首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >模板的选择性编译

模板的选择性编译
EN

Stack Overflow用户
提问于 2018-09-05 13:37:36
回答 1查看 60关注 0票数 0

是否有方法预编译某些模板实例化(类模板),但不是全部,以便在实例化时编译其余的模板(链接时出现w/o错误)?

为了演示这个问题,请考虑下面的示例:

代码语言:javascript
运行
复制
// 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"

代码语言:javascript
运行
复制
// 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的预编译代码,编译器将找到另一个编译版本。

那么,我如何避免这两个问题呢?我认为一个相关的问题是:“如何指定预编译的头完全编译特定模板参数的模板(仅)?”

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-05 13:40:41

您可以使用extern template来防止给定TU中模板的特定实例化。

代码语言:javascript
运行
复制
// src0.cpp

template class foo<int>;
    // Oblige instantiation of `foo<int>` in this TU

代码语言:javascript
运行
复制
// src1.cpp

extern template class foo<int>;
    // Prevent instantiation of `foo<int>` in this TU

只要src0src1连接在一起,你的程序就能工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52186537

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档