在C中的不同编译单元中是否多次编译模板类?
发布时间:2020-12-16 09:40:08 所属栏目:百科 来源:网络整理
导读:假设我有以下代码: // templateClass.h#ifndef TEMPLATE_CLASS_H#define TEMPLATE_CLASS_Htemplate typename Tclass tClass{public: tClass();};#endif// templateClassDef.inl#ifndef TEMPLATE_CLASS_DEF_INL#define TEMPLATE_CLASS_DEF_INLtemplate typen
假设我有以下代码:
// templateClass.h #ifndef TEMPLATE_CLASS_H #define TEMPLATE_CLASS_H template <typename T> class tClass { public: tClass(); }; #endif // templateClassDef.inl #ifndef TEMPLATE_CLASS_DEF_INL #define TEMPLATE_CLASS_DEF_INL template <typename T> tClass<T>::tClass() { } #endif // normalClass.h #include "templateClass.h" class normal { public: normal(); }; // normalClass.cpp #include "normalClass.h" #include "templateClassDef.inl" normal::normal() { tClass<int> a; } // main.cpp #include "templateClass.h" #include "templateClassDef.inl" #include "normalClass.h" int main() { tClass<int> a; normal b; return 0; } 请注意,inl文件不像通常那样包含在标头中,而是包含在源文件中(我知道这不是标准方式……这只是一个例子).请注意,normalcClass.cpp正在实例化tClass< int> main.cpp也是如此. 我很好奇编译器是否必须在每次遇到显式实例时从模板类构造实例化,考虑到它是相同的类型(即tClass< int>),即使两个实例都发生在单独的翻译单元(normalClass)中. cpp和main.cpp)?此外,这将增加编译时间(如果上一个问题的答案是肯定的,它将再次实例化,那么这也应该是肯定的)? 解决方法
通常,是的,模板类通常在每次编译器遇到时编译.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |