Few ideas to reduce template bloat

Norbert Nemec Norbert at Nemec-online.de
Thu Mar 25 07:44:15 PDT 2010


bearophile wrote:
> 4) C# avoids code bloat because it has a JIT and templates are instantiated at run-time. D can of course do the same if it uses the LLVM backend, but let's ignore this possibility for now.
> 
> 5) Java generics don't cause code bloat because it removes the types at runtime and uses boxed values. This can be type-safe, but it's less flexible than C++/D templates, and the boxing-unboxing decreases performance. On the other hand programming practice shows that in most programs not all functions have to be top performance. So a compromise can be invented (I have never found this idea elsewhere). An attribute like @boxed can be used to mark what function template arguments are boxed (and don't multiply the template instances).

Indeed, this is the very fundamental distinction between templates (C++) 
and generics (C# and Java).

Templates:
* have to be instantiated at compile time
* usable for meta-programming
* cannot be compiled or type-checked on its own
   --> not type-safe (i.e. if you don't set the constraints correctly, 
the instantiation may fail with an error message deep inside the 
template code)

Generics:
* Every template parameter must follow a clear interface.
* generic code can be compiled and fully type-checked on its own
* instantiation not needed at all but possible as optimization
   -> use boxed values without instantiation
   -> optionally instantiate at run-time/link-time/compile-time
     (analogous to function inlining)

Though both concepts have a large overlap, it is difficult to bridge the 
gap without adding significant complexity. Some experimental languages 
try to get the best of both ways by smearing or even giving up the 
distinction between compile-time and run-time. Though these attempts are 
very promising for the future, they are clearly beyond the pragmatic 
goals of D. D is clearly designed as language that can be compiled to a 
static binary.



More information about the Digitalmars-d mailing list