Template specialized functions creating runtime instructions?

ads relay.public.adnan at outlook.com
Tue Aug 20 23:48:04 UTC 2019


This piece of code creates a fizzbuzz string with template 
parameters.

auto fizzbuzz(uint N)() {
	string accumulate;
	return fizzbuzz!N(accumulate);
}

auto fizzbuzz(uint N)(ref string result) if (N % 3 && N % 5) {
	import std.conv : to;

	result ~= N.to!string ~ "\n";
	return fizzbuzz!(N - 1)(result);
}

auto fizzbuzz(uint N)(ref string result) if (!(N % 15)) {
	result ~= "FizzBuzz\n";
	return fizzbuzz!(N - 1)(result);
}

auto fizzbuzz(uint N)(ref string result) if (!(N % 3) && N % 5) {
	result ~= "Fizz\n";
	return fizzbuzz!(N - 1)(result);
}

auto fizzbuzz(uint N)(ref string result) if (!(N % 5) && N % 3) {
	result ~= "Buzz\n";
	return fizzbuzz!(N - 1)(result);
}

auto fizzbuzz(uint N : 0)(ref string result) {
	return result;
}

void main() {
	import std.stdio : writeln;

	fizzbuzz!50().writeln();
}


https://godbolt.org/z/hWENgc

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?


More information about the Digitalmars-d-learn mailing list