Q: What are the rules for emitting template code?

Steven Schveighoffer schveiguy at yahoo.com
Mon Oct 25 09:04:48 PDT 2010


On Sun, 24 Oct 2010 00:06:23 -0400, Austin Hastings <ah08010-d at yahoo.com>  
wrote:

> Howdy,
>
> This is a bit involved, so bear with me.
>
> Suppose I have a template, Decider(Args...) and some other templates,  
> Option1(...), Option2(...), etc.
>
> The job of Decider() is to decide, based on the given parameters, which  
> of the possible OptionN templates to use.
>
> Decider uses "static if" and some builtins and maybe some CTFE to  
> determine its result.
>
> Now:
>
> How much can Decider ask of one of the Option templates without that  
> template being expensively realized?
>
> Alternatively:
>
> What parts of an Option template have to be realized for Decider to do  
> its job?
>
> In particular:
>
> If Decider uses Option1.sizeof, does any Option1 code get emitted?
>
> If Decider uses some external function that makes use of type aliases in  
> Option1, (example:  Option1() { alias byte value_t; } ) does any Option1  
> code get emitted?
>
> If Decider uses some function defined inside the same module with  
> Option1, but NOT inside of Option1, does any/all of the Option1 code get  
> emitted?
>
> If Decider uses a static method of Option1, does any more of the Option1  
> code get emitted?
>
>
>
> Obviously, I am trying to ... decide ... how to do compile time  
> selection. But I'm also just a tad curious at the internals of the  
> template engine.

One of the major problems with the template system IMO is compile-time  
templates (that is, templates that are only used at compile time) are  
emitted into the executable, even though they are not used.

Take for example, isForwardRange(R).  A function like this:

void foo(R) if (isForwardRange!R)

is going to instantiate isForwardRange!R, which may instantiate other  
templates to check to see if isForwardRange is true.  But all these things  
end up in the executable, even though they aren't used.

Now, if you are concerned about executable footprint, this problem I think  
will eventually be solved (not sure if there is a bug report, but I think  
I've brought it up before, and the consensus is that it should not end up  
in the exe).  If you are concerned that the runtime of the *compiler*  
might be too long, then I'm afraid you are just going to have to deal with  
it.  Everything in a compiled language is focused first on the resulting  
executable.  It's perfectly normal for a compiler to take extra time  
compiling to make the executable more efficient.

-Steve


More information about the Digitalmars-d mailing list