digitalmars.D.learn - can I reuse statements?
- Jack (26/26) May 10 2021 mixin template seems to allow only declarations so if I put a if
- Paul Backus (24/50) May 10 2021 You can do it with a string mixin:
- Jack (2/27) May 10 2021 sounds good, thanks!
mixin template seems to allow only declarations so if I put a if
or case-statement in the body it doesn't work. I'd like to make
something like this work:
```d
switch(code) {
case X, Y: // that specific case repeats alot in
the code in different procedures
mixin handleXY;
default:
}
```
then
```d
mixin template foo()
{
auto c = arr[i]; // arr and i are available at
switch(code)'s scope
auto m = Message(...);
switch(code)
{
case BAA_A: c.doSomething(m); break;
case BAA_B: c.doSomething(m); break;
default: assert(0, "error");
}
}
```
May 10 2021
On Monday, 10 May 2021 at 21:01:53 UTC, Jack wrote:
mixin template seems to allow only declarations so if I put a
if or case-statement in the body it doesn't work. I'd like to
make something like this work:
```d
switch(code) {
case X, Y: // that specific case repeats alot
in the code in different procedures
mixin handleXY;
default:
}
```
then
```d
mixin template foo()
{
auto c = arr[i]; // arr and i are available at
switch(code)'s scope
auto m = Message(...);
switch(code)
{
case BAA_A: c.doSomething(m); break;
case BAA_B: c.doSomething(m); break;
default: assert(0, "error");
}
}
```
You can do it with a string mixin:
```d
// Note: q{ ... } creates a "token string", a special kind of
string literal
// that's used for code strings.
// See https://dlang.org/spec/lex.html#token_strings
enum string handleXY = q{
auto c = arr[i]; // arr and i are available at
switch(code)'s scope
auto m = Message(...);
switch(code)
{
case BAA_A: c.doSomething(m); break;
case BAA_B: c.doSomething(m); break;
default: assert(0, "error");
}
};
```
Usage:
```d
case X, Y:
mixin(handleXY);
```
May 10 2021
On Monday, 10 May 2021 at 21:10:13 UTC, Paul Backus wrote:On Monday, 10 May 2021 at 21:01:53 UTC, Jack wrote:sounds good, thanks![...]You can do it with a string mixin: ```d // Note: q{ ... } creates a "token string", a special kind of string literal // that's used for code strings. // See https://dlang.org/spec/lex.html#token_strings enum string handleXY = q{ auto c = arr[i]; // arr and i are available at switch(code)'s scope auto m = Message(...); switch(code) { case BAA_A: c.doSomething(m); break; case BAA_B: c.doSomething(m); break; default: assert(0, "error"); } }; ``` Usage: ```d case X, Y: mixin(handleXY); ```
May 10 2021








Jack <jckj33 gmail.com>