加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 检查是否已实例化类模板?

发布时间:2020-12-16 06:50:27 所属栏目:百科 来源:网络整理
导读:有没有一种简单的方法来查看某个类是否已在翻译单元中实例化? C Primer的练习询问每个带标签的语句,是否发生实例化: template typename T class Stack { };void f1(Stackchar); // (a)class Exercise { Stackdouble rsd; // (b) Stackint si; // (c)};int
有没有一种简单的方法来查看某个类是否已在翻译单元中实例化? C Primer的练习询问每个带标签的语句,是否发生实例化:

template <typename T> class Stack { };
void f1(Stack<char>); // (a)
class Exercise {
    Stack<double> &rsd; // (b)
    Stack<int> si; // (c)
};
int main() {
    Stack<char> *sc; // (d)
    f1(*sc); // (e)
    int iObj = sizeof(Stack< string >); // (f)
}

我不确定如何才能真正检查我的答案.我想也许我可以为每个类类型使用显式实例化(例如extern模板类Stack< char>),然后在程序中永远不会有相应的显式实例化定义.这样,如果事情被实例化,如果定义后来没有出现,那么链接器就会出错.

但是,编译器/链接器并不总是识别出这样的错误:

template <typename T> class A{ };
extern template class A<int>;
int main(){
    A<int> a; 
}

这在gcc 4.9.2上编译得很好.但是,如果这是我程序中唯一的目标文件,那么从N3337的[14.7.2] [11]我可以看出它应该是一个错误:

If an entity is the subject of both an explicit instantiation declaration and an explicit instantiation definition in the same translation unit,the definition shall follow the declaration. An entity that is the subject of
an explicit instantiation declaration and that is also used in a way that would otherwise cause an implicit instantiation (14.7.1) in the translation unit shall be the subject of an explicit instantiation definition somewhere in the program; otherwise the program is ill-formed,no diagnostic required.

(我猜测“不需要诊断”是为什么这不会引起错误?).或者,只要不完整的类类型不适用于表达式,就会发生实例化 – 这样我就可以通过删除Stack的定义来检查?

template <typename T> class Stack;

因此,每个不完整的类型错误对应于实例化发生的地方?

解决方法

您可以在可执行文件上使用nm工具.这将显示哪个文件包含函数定义. gcc还提供了一个标志,用于在执行链接时去除未使用的函数.

使用“-fdata-sections”编译以将数据保存在单独的数据部分和“-ffunction-sections”中以将函数保存在单独的部分中,因此如果未使用它们(数据和函数)可以被丢弃.链接“-gc-sections”以删除未使用的部分.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读