Why are template alias parameters broken?
Steven Schveighoffer
schveiguy at gmail.com
Fri Aug 27 19:14:36 UTC 2021
On 8/27/21 2:47 PM, Menshikov wrote:
> It's work:
>
> ```d
> template Foo(alias var)
> {
> void inc() { var++; }
> }
>
> void main()
> {
> int v = 4;
> alias foo = Foo!(v);
> foo.inc();
> assert(v == 5);
> }
> ```
> But it doesn't work:
> ```d
> template Foo(alias var)
> {
> void inc() { var++; }
> }
>
> void main()
> {
> struct V{
> int a;
> }
> auto v = V(4);
> alias foo = Foo!(v.a);
> foo.inc();//err
> assert(v.a == 5);
> }
> ```
> Hence this applies to Alias!() and AliasSeq!()
Aliases to expressions don't work. They have to be symbols, type
keywords (e.g. `int`), or compile-time values. `v.a` is an expression.
It's quite an annoying limitation, I agree.
To work around, you can do:
```d
template Foo(alias var)
{
void inc() {var.a++}
}
```
and then pass `v` instead of `v.a`.
-Steve
More information about the Digitalmars-d
mailing list