Mixin template parameters / mixin template literals
"Luís
"Luís
Tue Apr 23 19:18:03 PDT 2013
Consider:
sort!("a > b")(array);
This is almost perfect, except for "a > b" being a string instead
of "real" code. If "a > b" was an actual block of code it could
be syntax highlighted by the editor, directly grammar checked by
compiler, etc. The only impediment to that is that a and b are
declared in the sort() body scope, so "a > b" has to be mixed-in
later in sort().
An alternative is using a lambda:
sort!((a, b) => a > b)(array);
Now we have code which is directly parsed and highlighted, but it
is more verbose (is there any other difference? I suppose there's
no performance penalty, because the templated sort() creates a
function from the string "a > b" anyway).
It would seem that the best of both worlds would be for sort() to
specify that the "less" type parameter could be actual code, but
that it should be mixed-in inside sort(). Well, since we have
lazy parameters, I was wondering why couldn't we have mixin
parameters. So I tried this, which works:
// create our "a > b" as code (not string) that is mixed-in
later
mixin template Greater() {
auto Greater = () => a > b;
}
// example of a sort which supports template mixins
void foo_sort(alias G = Greater, Range)(Range r)
{
bool funG(Range)(ElementType!(Range) a,
ElementType!(Range) b)
{
mixin G;
return Greater(); // Greater() because G() doesn't
work (unhelpful alias, see previous thread)
}
sort!(funG!(Range))(r);
}
void main()
{
int[] array = [3, 1, 5, 2, 7];
foo_sort!(Greater)(array);
writefln("%s", array);
}
So, the infrastructure seems to be there, we just had to declare
Greater() outside the sort() call site because we have neither
mixin template parameters nor mixin template literals. If we had
one of those we could do either:
void foo_sort(mixin G, Range)(Range r) { ... } // or mixin
template G
foo_sort!(a > b)(array);
or
foo_sort!({a > b})(array); // some kind of mixin template
literal
Of course, this isn't anything specific to template functions and
sort. This is a kind of macro, just like the lazy type specifier,
so I it would be useful in other places.
OK, so this is probably a bit crazy, but I had to share these
thoughts. Feel free to proceed to demolish all of this ;-)
More information about the Digitalmars-d
mailing list