c – 同一翻译单元中的模板类和相应的extern模板类
这是C 11中extern模板的正确用法吗? (可以是extern模板类和相应的模板类在同一个翻译单元中可见吗?)
// example.hpp: #pragma once template< typename T > class C { void f(T); }; // question is about the next two lines extern template class C< float >; extern template class C< double >; // example_def.hpp: #include "example.hpp" template< typename T > void C< T >::f(T) { //... smth. practicable } // example.cpp: #include "example_def.hpp" template class C< float >; template class C< double >; // other.hpp: #pragma once void g(); // other.cpp: #include "other.hpp" #include "example.hpp" // maybe those two lines should be here instead? void g() { C< float >(); C< double >(); } // main.cpp: #include "example.hpp" #include "other.hpp" // ...and here? int main() { C< float >(); C< double >(); g(); return 0; } 解决方法
是的,如果定义(没有extern)遵循声明,则extern模板类规范(标准称为显式实例化声明)和模板类规范(标准称为显式实例化定义)可以在同一个转换单元中(与extern):
(强调我的).术语显式实例化声明和显式实例化定义在此定义:
这些显式实例化的效果如下: >显式实例化声明(使用extern)可防止所有隐式实例化生效(内联函数和类模板特化除外,§14.7.2/ 10). 普通的留言 这可能令人困惑,当您期望许多不同的用户为许多不同类型实例化模板时,这可能不是一个好主意.但是,如果不同类型的实例化数量很少并且您可以预测它们,那么这是明智的.当然,您必须确保有一个(或几个).cpp文件包含所需的所有实例化的显式实例化定义,并且其对应的目标文件在构建时与项目链接. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |