Currently templates can consists only from declarations, so it's not possible to put there statements. It causes following:
below does not compile:
-------------------
template init() {
a = 5;
}
void main() {
int a;
mixin init;
}
-------------------
but below compiles:
-------------------
import std.stdio;
template init() {
void func() {writefln(a);}
}
void main() {
int a;
mixin init;
func();
}
--------------------
while both template bodies are syntacticly wrong.
------------
I think that statements should be allowed in templates or another mechanism should be introduced and template mixins should be depreciated.
Comment #1 by davidl — 2007-12-21T02:48:32Z
It's quite critical in my opinion.
So I mark this severity to major
Comment #2 by smjg — 2007-12-29T12:47:31Z
Depreciated? What?
Or do you mean deprecated? Still, I disagree. Templates are designed to contain declarations, not statements. Blocks of statements are a different concept from blocks of declarations. Declarations can be in any scope; statements can only be within a function.
So my thought is that template mixins should remain for inserting declarations in whatever scope, and something new should be created for inserting statements in a function.
Comment #3 by clugdbug — 2012-11-12T07:21:56Z
Current behaviour is intentional.
Even this does not compile:
---------
template init() {
a = 5;
}
---------
This is an enhancement request.
Comment #4 by andrej.mitrovich — 2013-02-04T18:01:08Z
Worst case scenario you can still use string mixins:
string init()
{
return q{
a = 5;
};
}
void main()
{
int a;
mixin(init);
}
So it's not all bad.
Comment #5 by andrei — 2016-10-14T00:49:11Z
This is too large an enhancement for bugzilla. If such is deemed necessary, the DIP approach must be taken.