Templates with scope
bauss
jj_1337 at live.dk
Wed Jul 21 07:16:43 UTC 2021
Is there a way to make this logic work without using a mixin
template.
I'd prefer if using a plain template was possible, rather than
using a mixin template, because it introduces some extra
boilerplate.
```d
template CanCompile(alias symbol)
{
enum CanCompile = __traits(compiles, { mixin(symbol.stringof
~ " = 10;"); });
}
mixin template CanCompile2(alias symbol)
{
enum couldCompile = __traits(compiles, {
mixin(symbol.stringof ~ " = 10;"); });
}
void main()
{
int x = 20;
// Fails:
static if (CanCompile!x)
{
x = 10;
}
// Okay:
mixin CanCompile2!x;
static if (couldCompile)
{
x -= 10;
}
writeln(x); // Output: 10
}
```
If it was possible to do it like this:
```d
static if (mixin CanCompile2!x)
{
x -= 10;
}
```
Then it wouldn't be a problem, but unfortunately it's not.
I know why the template fails, so I'm not looking for the
reasoning behind it, but is there not a way to avoid using mixin
templates because I don't want to introduce a variable into the
scope and I want to keep the code as short as possible.
Basically my use-case is just to test if certain expressions are
possible in the current scope based on a given symbol, but I'd
want to just test it in a static if statement.
I'm aware that I can just put the __traits(compiles) directly
into the code, but what I'm trying to achieve here is a wrapper
around that so I don't have some ugly boilerplate code.
More information about the Digitalmars-d
mailing list