RFC: generic safety, specialized implementation?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Jan 19 19:29:37 UTC 2018


On Fri, Jan 19, 2018 at 07:18:22PM +0000, Luís Marques via Digitalmars-d wrote:
[...]
>     void combulate(T)(T* item)
>     {
>         // ... lots of code here
>         item.next = ...;
>     }
[...]
[...]
> This catches the bug, but will have the disadvantage of generating
> code for the various types to which combulate is specialized, even
> though the body of the function template doesn't rely on anything that
> varies between the specializations.

Yeah, I think this is one area where the way the compiler implements
templates could be improved.  Quite often, in a complex template
(whether it's a template function or a template aggregate like a struct
or class) only a subset of the code actually depends on the template
arguments. Nevertheless, the compiler duplicates the entirety of the
code in the generated template. This leads to a lot of template bloat.

I'm not sure how possible it is in the current compiler implementation,
but it would be nice if the compiler were a bit smarter about
instantiating templates.  If an instantiated function (could be any
subset of the code, but granularity at the function level is probably
easiest to implement) would not result in code that differs from other
instantiations in the generated IR, only emit the code if it hasn't been
emitted yet; otherwise just alias that particular instantiation to the
previous instantiation.

Perhaps an enhancement request could be filed for this.


[...]
> That is problematic in the context where I'm using this (embedded
> systems). So instead I've started using a mixed approach, with generic
> code that checks for the appropriate type, but delegates the actual
> work to a non-templated function (a fully specialized function
> template in my actual case), except in the cases where the actual code
> is small enough or the specialization significantly improves the
> performance. Something like this:
[...]
> So far this seems to be working well for me. Do you have experience
> writing this kind of code? Do you have any advice that might be
> relevant to this situation?
[...]

Yeah, basically, this is just doing what I described above by hand.
I've done similar refactorings before, to reduce template bloat. It
certainly seems to work well.  However, it would be nice if the compiler
automated such rote work for us.


T

-- 
Help a man when he is in trouble and he will remember you when he is in trouble again.


More information about the Digitalmars-d mailing list