Is this a correct way to make this code working at compile time?

Andrey Zherikov andrey.zherikov at gmail.com
Mon Nov 18 21:59:43 UTC 2024


Below is the reduced code that replicates my problem.
I'm trying to remember a value (of some type) that can be used at 
run time (assigned to a variable). "Remembering" must be done at 
compile time because it's a part of UDA.
```d
// I can't get rid of this struct because it contains a lot of 
information and needed to perform business logic (but I can 
change the content):
struct S(T)
{
     T value;

     // I prefer to keep `const` here
     void f(ref T v) const { v = value; }
}

// I can't get rid of this function as this is public API and 
actually used in UDA:
auto create(VALUE)(VALUE value)
{
     return S!VALUE(value);
}

// Case with `string` work perfectly
{
     enum o = create("abc");
     string v;
     o.f(v);
     v.writeln;
}
// But `string[]` doesn't work (complain is for `S.f`):
// Error: cannot implicitly convert expression `this.value` of 
type `const(string[])` to `string[]`
{
     enum o = create(["abc"]);
     string[] v;
     o.f(v);
     v.writeln;
}
```

If I change S.f to either `void f(ref T v) const { v = cast(T) 
value; }` or `void f(ref T v) const { v = value.to!T; }` then 
everything works. Is this a correct/safe way to go since I'm 
copying `const string[]` to `string[]`?


More information about the Digitalmars-d-learn mailing list