Template wizardry and its cost

Bastiaan Veelo Bastiaan at Veelo.net
Mon Jun 20 14:17:17 UTC 2022


On Monday, 20 June 2022 at 12:59:28 UTC, Steven Schveighoffer 
wrote:
> 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);
> }
> ```

Wow. Man, this is interesting. My hat is off.

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

You have put a big grin on my face, I like your potion!

-- Bastiaan.


More information about the Digitalmars-d mailing list