On Thursday, 6 March 2014 at 18:31:02 UTC, Frustrated wrote:
On Thursday, 6 March 2014 at 17:27:35 UTC, Steve Teale wrote:
Pretty much what the subject says. Why can't template mixins
include statements ans so on?
Is it just too hard, or is it just too much like C macros?
Steve
template mixins mix in directly into the code as if you typed
them. If they contained statements then you could mixin
statements into classes, say, and it would then be illegal.
I guess there is no reason per se, but I guess that wasn't the
desired behavior for template mixins. I imagine there could be
a definite downside to having template mixins containing
statements. Also, they can't be self contained.
e.g.,
mixin template C()
{
i = i + 1; // invalid
}
...
int i = 0;
mixin C();
The template itself can't be semantically checked in place
because i is unknown inside the template. (it is not self
contained so to speak)
In any case, just seems wrong for templates to do that. They
are not grouping expressions but grouping definitions and
declarations of things so you don't have to do them multiple
times.
string mixins, OTOH, could do the above.
template C()
{
string C()
{
return "i = i + 1;";
}
}
...
int i = 0;
mixin(C);
and this will work. This is because the statement is contained
within a string and the compiler simply inserts the string
directly. The template can still be validated in place(since "i
= i + 1" is a string and has no other meaning in the template).
Interesting. I regularly use template mixins referring to 'this'
and they work fine. e.g.:
mixin template Bar()
{
public int getFoo()
{
return this.foo;
}
}
class Foo
{
private int foo;
mixin Bar;
}