3 ms·
The best way that I know of to do this is the """ "Manual" export templates """ idea discussed here: http://warp.povusers.org/programming/export_templates.html
by senkora 2y ago
The best way that I know of to do this is the """ "Manual" export templates """ idea discussed here: http://warp.povusers.org/programming/export_templates.html http://warp.povusers.org/programming/export_templates.html
(It's a great post in general. N.B. that it's also quite old and export templates have been removed from the standard for quite some time after compiler writers refused to implement them.)
TL;DR: Declare your templates in a header, implement them in a source file, and explicitly instantiate them inside that same source file for every type that you want to be able to use them with. You lose expressiveness but gain compilation speed because the template is guaranteed to be compiled exactly once for each instantiation.
- senkora 2y ago> You lose expressiveness Or more, correctly, the following happens: 1. You gain the ability to use the compilation unit's anonymous namespace instead of a detail namespace, so there is better encapsulation of implementation details. The post author stresses this as the actual benefit of export templates, rather than compile times. 2. You lose the ability to instantiate the template for arbitrary types, so this is probably a no-go for libraries. 3. Your template is guaranteed to be compiled exactly once for each explicit instantiation. (Which was never actually guaranteed for real export templates).
- jcranmer 2y agoYou can declare a template in a header file, and only provide its definition (and hence expansion) in a source file. See for example Firefox doing this for its string implementation here: https://searchfox.org/mozilla-central/source/xpcom/string/nsTSubstring.h#289 https://searchfox.org/mozilla-central/source/xpcom/string/ns... (extern template declarations are at the end of the header file, and the actual template definitions are in https://searchfox.org/mozilla-central/source/xpcom/string/nsTSubstring.cpp https://searchfox.org/mozilla-central/source/xpcom/string/ns...). Which is to say, "extern template" is a thing that exists, that works, and can be used to do what you want to do in many cases. The "export template" feature was removed from the language because only one implementer (EDG) managed to implement them, and in the process discovered that a) this one feature was responsible for all of their schedule misses, b) the feature was far too annoying to actually implement, and c) when actually implemented, it didn't actually solve any of the problems. In short, when they were asked for advice on implementing export, all the engineers unanimously replied: "don't". (See https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1426.pdf https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n14... for more details).