Template specialized functions creating runtime instructions?

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Aug 21 00:04:37 UTC 2019


On Tue, Aug 20, 2019 at 11:48:04PM +0000, ads via Digitalmars-d-learn wrote:
[...]
> In the generated assembly, it looks like it is creating a lot of
> runtime instructions, contrary to my belief that templated codes are
> purely compile-time. I was expecting that the compiler would deduce
> the fizzbuzz string until 50 in compile-time and just print it in the
> run-time. Why is this not the case?

Let's clear up a few things:

1) "Template code" is not the same thing as "compile-time". Templates
are essentially "code stencils", used for generating multiple copies
(usually with variations) of the same *runtime* code.  The *expansion*
of the template is done at compile-time, but the *result* is often
runtime code (e.g., template functions, like you have here).

2) Deducing the string as you describe would require CTFE (compile-time
function evaluation), which usually isn't done unless the result is
*required* at compile-time.  The typical way to force this to happen is
to store the result into an enum:

	enum myStr = fizzbuzz!...(...);
	writeln(myStr);

Since enums have to be known at compile-time, this forces CTFE
evaluation of fizzbuzz, which is probably what you're looking for here.

3) And BTW, don't confuse "templates" and CTFE, because they are not the
same thing, in spite of being both done "at compile-time". See:

	https://wiki.dlang.org/User:Quickfur/Compile-time_vs._compile-time


T

-- 
Those who've learned LaTeX swear by it. Those who are learning LaTeX swear at it. -- Pete Bleackley


More information about the Digitalmars-d-learn mailing list