On Thursday, 1 August 2013 at 18:09:54 UTC, H. S. Teoh wrote:
On Thu, Aug 01, 2013 at 07:52:28PM +0200, JS wrote:
On Thursday, 1 August 2013 at 17:47:00 UTC, H. S. Teoh wrote:
>On Thu, Aug 01, 2013 at 07:12:51PM +0200, John Colvin wrote:
>>On Thursday, 1 August 2013 at 17:09:07 UTC, JS wrote:
>>>If I have a bunch of templates that are only used for code
>>>generation, are they removed in the binary(since they are
>>>not
>>>needed)?
>>
>>templates don't exist in binaries.
>
>Templates are like cookie molds, you use them to generate
>lots of
>(almost) identical cookies, but you never serve the mold to
>the
>customer. ;-)
>
>
>T
But what about the functions that exist in them?
Like I said, cookie molds. You use the mold to press cookies,
but only
the cookies are served, not the mold. The mold may be very
complicated,
containing subcookies attached to bigger cookies, but whatever
is
pressed (i.e., instantiated) is what's served on the dinner
plate. The
mold always remains in the kitchen.
template A()
{
void A()
{
B();
}
void B() { }
}
is everything in the template removed 100% or is there junk
that the
compiler doesn't remove?
There is nothing to remove. If you instantiated the template,
then you
get a copy of everything in it. The number of copies equals the
number
of distinct instantiations. The template itself is just a mold,
an
abstract entity that doesn't exist in binary form. What it does
is to
serve as a mold (hence, "template") to make code. So if you use
to make
10 copies of the code, that's what you'll get in your
executable. If
your template contains 5 functions, then each instantiation
produces 5
copies of those functions. Simple as that.
Of course, not all code produces binary data -- enum and alias
definitions don't produce any binary code, for example --
they're just
logical entities that only exist at compile time. So if you
have an enum
inside a template, it will get copied however many times you
instantiate
the template, but none of those copies end up in the executable
because
they're just declarations, not actual code or data.
Ok, I'm not talking about the template itself but what is
contained in the template. It is obvious that templates can
"insert" stuff into the binary.
a mixin template can easily do that.
Now are you telling me that
template A()
{
void foo() { writeln("asdf"); }
}
void main()
{
A!().foo();
}
does not create a function foo in the binary? That it is
equivalent to just calling writeln("asdf"); directly? (exact same
code)
e.g., it is the same as
void main() { A!().foo(); }
cause when I actually debug I see a function call to foo.
So, saying that templates are like cookie cutter doesn't prove
anything.
If I have
void main() { }
the binary file is is 150kB. If I add import std.stdio; It jumps
to 300kB.
So the linker and compiler are not removing all untouched code.