On Sunday, 2 September 2018 at 18:07:10 UTC, Jonathan M Davis
wrote:
On Sunday, September 2, 2018 7:21:05 AM MDT bauss via
Digitalmars-d wrote:
Is there a reason why you cannot create a separate scope
within a static foreach?
The below will not compile:
```
enum a = ["a" : "a", "b" : "b", "c" : "c"];
static foreach (k,v; a)
{
{
enum b = k;
enum c = v;
}
}
```
It works if it's in a function of course.
This creates a big limitation when you're trying to ex. loop
through members of inherited classes, interfaces etc. and then
want to store the information in variables, because you cannot
do it. Which means to work around it you have to do it all in
an ugly one-liner.
Is it intended behavior? If so, why? If not is there a
workaround until it can be fixed?
If you're not inside a function, why would it even be useful to
be able to do that? That would be the equivalent of
{
enum b = "a";
enum c = "a";
}
{
enum b = "b";
enum c = "b";
}
{
enum b = "c";
enum c = "c";
}
Creating scopes like that isn't legal outside of a function
(hence the compiler error), but even if it were, what good
would it do you? There's no way to refer to those scopes. The
only way that such declarations would make sense is if they're
inside scopes with their own names so that they can be referred
to via those names (e.g. inside a struct or template) or if
they aren't in separate scopes and have unique names (which
would mean giving them names other than b and c rather than
trying to scope them). I fail to see why what you're
complaining about here would even be useful.
Now, the fact that it's a bit of a pain to give each of those
enums a unique name can certainly be annoying, and that's a
problem with static foreach in general, but I don't understand
why creating an extra scope like you're trying to do here would
be at all useful outside of a function. What are you really
trying to do here?
- Jonathan M Davis
Let me demonstrate why it's useful with just this unmaintainable
piece of code:
```
final class ClassName : SoapBinding, Interface
{
public:
final:
this()
{
super();
}
import __stdtraits = std.traits;
static foreach (member; __traits(derivedMembers, Interface))
{
mixin
(
mixin("(__stdtraits.ReturnType!" ~ member ~ ").stringof") ~
" " ~
member ~
"(" ~
mixin("parameters!" ~ member) ~
") { /* Do stuff ... */ }"
);
}
}
```
Woud be so much more maintainable if I could have each statement
into a variable that could be maintained properly.