简体   繁体   English

枚举模板的所有实例

[英]Enumerating all instantiations of template

I am reading on type erasure: 我正在阅读类型擦除:

Andrzej's C++ blog Type erasure — Part I Andrzej的C ++博客类型擦除-第一部分

Where I come across the following text: 我在哪里遇到以下文字:

unless you can enumerate all instantiations of your template in advance, you have to include the body of each function template in the header file, you cannot separate the declaration from the implementation 除非您可以事先枚举模板的所有实例化,否则必须在头文件中包含每个函数模板的主体,否则无法将声明与实现分开

Is enumerating all instantiations of the template the same as explicit instantiation pointed out in answer to the following question? 列举模板的所有实例化是否与对以下问题的回答中指出的显式实例化相同?

Why can templates only be implemented in the header file? 为什么只能在头文件中实现模板?

Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need: 另一个解决方案是使实现分离,并显式实例化所需的所有模板实例:

// 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

Mostly yes. 通常是的。

What it boils down to is "can you know everywhere this is used?". 归结为“您是否知道使用它的所有地方?”。 The authors of std::vector<T> can't know all the types T will be substituted for. std::vector<T>的作者知道T将替代所有类型。

That's the "enumerate all instantiations" step, which is followed by "write down all the explicit instantiations". 这是“枚举所有实例化”步骤,然后是“写下所有显式实例化”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM