On Wednesday, 12 April 2017 at 11:06:13 UTC, Juanjo Alvarez wrote:
Hi!
With "alias this" accepting runtime variables I'm struggling to
understand the difference between a generic function with an
"alias this" parameter and another one with a "runtime"
parameter of template type.
Example:
// ---- example code ----
import std.stdio: writeln;
void writevalue1(alias param)() { writeln(param); }
void writevalue2(T)(T param) { writeln(param); }
void main() {
import std.random: uniform;
auto someNum = uniform(0, 1000); // runtime value
writevalue1(someNum);
someNum = uniform(0, 1000);
writevalue2(someNum);
}
// ---- example end -----
Since both versions work with runtime values, what's are the
differences? When I should prefer one version over the other?
If objdump is not lying to me, both calls jump to the same
assembly and the only diffence is that the call to writevalue1
does a "mov -0x8(%rdi),%edi" just before the callq instruction.
(As noted by Mike the examples you present are actually template
alias parameters, not alias this which affects name lookup.)
There are three kinds of template parameters types, values and
aliases.
I assume you understand what the first two _do_ in terms of
parameterisation.
Alias parameters are for symbols, and are used generally when the
thing you want to template on not a value or a type (although
alias parameters can accept anything).
These typically include lambdas e.g. the predicate to
std.algorithm.filter or the transformation to std.algorithm.map,
(global) variables to do introspection (for e.g. logging).