且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C ++ 20模块中使用模板显式实例化?

更新时间:2023-09-18 08:46:04

模块使快速构建案例变得非常容易。他们在支持客户实例化,但避免重建具有明确实例化专长的客户方面做得并不多;从理论上讲,由于避免了重复的工作,构建速度通常更快,因此无需扭曲程序即可节省更多时间。

Modules make the "fast single build" case very easy. They don’t do much for the "support client instantiation but avoid rebuilding clients of the explicitly instantiated specializations" case; the theory is that the generally faster builds from avoiding repeated work makes it unnecessary to contort the program so as to save even more time.

全部您要做的是在模块界面中放置一个明确的实例化定义

All you do is put an explicit instantiation definition in the module interface:

export module A;
export template<class T>
inline void f(T &t) {++t;}
template void f(int&);
template void f(int*&);

导入程序无需实例化 f 即使功能模板是 inline (这可能需要非模块化代码中的其他实例化),这两种类型中的任何一种也是如此。一个典型的实现将那些实例化的结果缓存在编译后的模块接口文件中,并具有足够的详细信息以内联到导入器中(以及将模板本身缓存有足够的详细信息以进一步实例化它)。

Importers will not have to instantiate f for either of those two types, even though the function template is inline (which may require additional instantiations in non-modular code). A typical implementation caches the results of those instantiations in the compiled module interface file with sufficient detail to inline calls in an importer (as well as caching the template itself with sufficient detail to instantiate it further).

您当然也可以使用显式实例化 declaration ,只需在接口中声明模板,然后定义模板并将显式实例化 definitions 放入一个模块实现单元,但这与头文件的工作原理没有什么不同。

You can of course also use an explicit instantiation declaration with just a declaration of the template in the interface and define the template and put explicit instantiation definitions in a module implementation unit, but that’s no different from how header files work.