【问题标题】:Enumerating all instantiations of template枚举模板的所有实例
【发布时间】: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


【解决方案1】:

大部分是的。

归结为“你能知道它在哪里被使用吗?”。 std::vector&lt;T&gt; 的作者无法知道T 将被替换的所有类型。

这是“枚举所有实例化”步骤,然后是“写下所有显式实例化”。

【讨论】: