Template wizardry and its cost

Steven Schveighoffer schveiguy at gmail.com
Mon Jun 20 12:59:28 UTC 2022


On 6/20/22 4:37 AM, Bastiaan Veelo wrote:

> But I don't think I'll go through with it this way. My problem is the 
> template instantiation for every individual translatable string literal. 
> I'd like to think the consequences are insignificant, but in large code 
> bases I fear they won't be. And the issue is that only for 
> `version(extractStrings)` the string needs to be a template argument, 
> otherwise you'd want it to be an ordinary function argument. Maybe this 
> is possible to achieve with string mixins, but probably not without 
> getting much more verbose.
> 
> I am ready to be amazed with more wizardry, or to be convinced not to 
> worry because inlining or something (it doesn't inline). Until then, I 
> am thinking an external tool based on `libdparse` or dmd-as-a-library is 
> probably the better approach; however awesome D is :-)

Let me dust off my wand ;)

```d
struct TranslatedString {
     private string _str;
     string get() {
         return curLang.translate(_str);
     }
     alias get this;
}
template gettext(string str) {
     version(extractStrings) {
         shared static this() {
             ++translatableStrings.require(str); // use require here, 
even though the ++ works without it.
         }
     }
     enum gettext = TranslatedString(str);
}
```

What does this do? It *still* generates the template, but the key 
difference is that the `TranslatedString` type is not a template. An 
enum only exists in the compiler, it's as if you pasted the resulting 
code at the call site. So it should not take up any space, maybe 2 words 
for the string reference. But only one `TypeInfo` (if that's even 
needed, I'm not sure), and a minor CTFE-call for the construction.

It *will* take up space in the symbol table, but that goes away once 
compilation is done.

But in general, one should not be afraid of writing templates in D. I 
think there may be some room for improvement for performance with 
compiler hints, or improvements without them.

-Steve


More information about the Digitalmars-d mailing list