Struct template instancing inside of class failed

monkyyy crazymonkyyy at gmail.com
Fri May 2 22:51:24 UTC 2025


On Friday, 2 May 2025 at 21:58:50 UTC, Denis Feklushkin wrote:
> Hi!
>
> I'm not sure if this is an issue or if it was intended this way.
>
> ```d
> class C(alias a) {
>     pragma(msg, "class body: ", a.stringof);
>     int internal;
>     this(int unused){
>         pragma(msg, "class ctor: ", a.stringof);
>         internal = a;
>     }
> }
>
> struct S(alias a) {
>     pragma(msg, "struct body:", a.stringof);
>     int internal;
>     this(int unused){
>         pragma(msg, "struct ctor:", a.stringof);
>         internal = a;
>     }
> }
>
> class Test {
>     int field = 123;
>
>     C!field c;
>     S!field s;
>
>     this(){
>         c = new C!field(777); // ok
>         assert(c.internal == 123);
>
>         // Error: accessing non-static variable `field` 
> requires an instance of `Test`
>         s = S!field(777);
>     }
> }
>
> void main() {
>     auto t = new Test;
> }
>
> ```
>
> Compiler output:
> ```
> class body: field
> struct body:field
> class ctor: this.this.field
> struct ctor:field
> app.d(20,20): Error: accessing non-static variable `field` 
> requires an instance of `Test`
>         internal = a;
>                    ^
> Error dmd failed with exit code 1.
> ```
>
> I suspect that class stores template parameter "a" in some 
> hidden fields and this behaviour impossible for POD structs?

Theres allot of spooky things here

it will compile if you add static to `static int field = 123;`

if you want a spooky reference to a variable I suggest my 
"innate" code avoid this construction logic your playing with

```d
template innate(T,T startingvalue=T.init,discrimination...){
	T innate=startingvalue;
}
alias field=innate!(int,123,"field");
```

if you dont need it run time you should pass ints to templates 
explictly where possible `struct S(int a) {` etc.


More information about the Digitalmars-d mailing list