【发布时间】:2023-04-28 02:09:02
【问题描述】:
我正在阅读类型擦除:
Andrzej's C++ blog Type erasure — Part I
我在哪里看到以下文字:
除非您可以枚举模板的所有实例 提前,您必须在 头文件,您不能将声明与 实施
枚举模板的所有实例化是否与回答以下问题时指出的显式实例化相同?
Why can templates only be implemented in the header file?
另一种解决方案是将实现分开,并且 显式实例化您需要的所有模板实例:
// Foo.h
// no implementation
template <typename T> struct Foo { ... };
//----------------------------------------
// Foo.cpp
// implementation of Foo's methods
// explicit instantiations
template class Foo<int>;
template class Foo<float>;
// You will only be able to use Foo with int or float
【问题讨论】:
-
@L.F.编辑了原始问题
-
好的。是的,博主显然指的是显式实例化。您必须提前知道要使用的所有特化,才能使用显式实例化来分离实现。
-
枚举模板的所有实例化是开发人员创建这些实例化列表的操作。拥有该列表是能够显式实例化模板所必需的。
标签: c++ templates explicit-instantiation