Thread overview
Is this a correct way to make this code working at compile time?
3 days ago
Andrey Zherikov
3 days ago
Dom DiSc
2 days ago
Andrey Zherikov
3 days ago

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.

// 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[]?

3 days ago

On Monday, 18 November 2024 at 21:59:43 UTC, Andrey Zherikov wrote:

>

Is this a correct/safe way to go since I'm copying const string[] to string[]?

Copying constants to variables is something absolutely normal. If this wouldn't work, how would you program at all?
So, yes this is safe and correct.
What you should NOT do is casting const away (without copying).

2 days ago

On Tuesday, 19 November 2024 at 00:27:51 UTC, Dom DiSc wrote:

>

On Monday, 18 November 2024 at 21:59:43 UTC, Andrey Zherikov wrote:

>

Is this a correct/safe way to go since I'm copying const string[] to string[]?

Copying constants to variables is something absolutely normal. If this wouldn't work, how would you program at all?
So, yes this is safe and correct.
What you should NOT do is casting const away (without copying).

Thank you!