Folding similar templates into one

Jonathan M Davis jmdavisProg at gmx.com
Wed Jun 26 20:47:21 PDT 2013


On Thursday, June 27, 2013 04:03:34 Meta wrote:
> I'd like to ask, however, why should this be? The arguments line
> and file will only ever be strings and ints. They don't vary in
> type, only value, and changing those values will not affect how
> the function works. You could easily substitute out "exception.d"
> with "stdio.d", and the functionality will be unchanged.

That's _very_ dependent on what the function does. A prime counter-example 
would be overloaded operators like opBinary which uses their string template 
arguments in mixins within the function, thereby generating completely 
different functions. And I believe that that is by far the more common use of 
strings as template parameters.

Also, when using strings and integral values such as __FILE__ and __LINE__, 
the functions _do_ have different code.

auto foo(string file = __FILE__, size_t line = __LINE__)(Bar b)
{
 auto f = file;
 auto l = line;

 ....
}

ends up generating different code depending on the values of file or line. The 
code is _not_ identical. The only way for the code not to vary is for those 
arguments to be runtime arguments. If they're compile-time arguments, then by 
definition, they affect the generated code if they're ever used.

Yes, it is theoretically possible for the compiler to use the same template 
definition under certain circumstances (especially if you're dealing with 
something like a templated struct that ultimately ends up with exactly the 
same layout across multiple instantiations), but the only way that the 
compiler could avoid duplicating the code with something like __FILE__ and 
__LINE__ being used as template arguments is to translate them into function 
arguments, because if the function has only one definition, then it can't have 
different values for the file or line number.

- Jonathan M Davis


More information about the Digitalmars-d mailing list