Details of the inline import idiom

Paul Backus snarwin at gmail.com
Fri Sep 27 03:53:43 UTC 2019


On Friday, 27 September 2019 at 03:37:53 UTC, TheGag96 wrote:
> I was looking back at the inline import idiom article[1]. One 
> of the purported benefits of doing something like 
> from!"std.datetime".SysTime was that doing so wouldn't go and 
> import the entirety of the module into the namespace and slow 
> down compile time / bloat the binary. But how is this so? When 
> the template ends up doing import from = std.datetime, doesn't 
> that go and import everything, not just SysTime? Or is there 
> some detail I'm missing? Thanks!
>
> [1]: https://dlang.org/blog/2017/02/13/a-new-import-idiom/

If you write an import statement inside a template, that import 
isn't processed until the template is instantiated.

For imports that are used inside the body of a template this is 
easy to do--you just put the import statement in the body of the 
struct/class/function/whatever. For imports used in template 
constraints or template function parameter lists, however, you 
can't do this; there's no place for the import to go. You end up 
having to put it at the top level of the module, and pay the cost 
for processing it even if the template that uses it is never 
instantiated.

Of course, if you do end up instantiating the template, the 
import is processed regardless, and you don't gain anything. So 
this trick is really only worth it in modules that contain a 
bunch of different templates, only some of which will end up 
being used in any given program--in other words, modules like the 
ones in D's standard library.


More information about the Digitalmars-d-learn mailing list