On Monday, 8 August 2022 at 05:38:31 UTC, rempas wrote:
In the following struct (as an example, not real code):

```
struct TestArray(ulong element_n) {
  int[element_n] elements;

  this(string type)(ulong number) {
    pragma(msg, "The type is: " ~ typeof(type).stringof);
  }
}
```

I want to create it and be able to successfully initialize the template parameters of the constructor but until now, I wasn't able to find a way to successfully do
that. Is there a way you guys know?  I have tried the following:

```
void main() {
  // Doesn't work
  auto val = TestArray!(10, "int")(60);

  // Doesn't work either
  auto val = TestArray!(10).TestArray!("int")(60);

  // Neither this works....
  auto val = TestArray!(10).this!("int")(60);
}
```

As with every question I make, the solution must be "betterC" compatible so I can use it.
Thanks a lot!

I would move the constructor out of the struct into a helper function, either global or as a static member:

```d
TestArray!n testArray(ulong n, string type)(ulong number) {
    TestArray!n ret;
    pragma(msg, "The type is: " ~ typeof(type).stringof);

    ret.something = something; // do your constructor logic here

    return ret;
}
```

which you can then use:

```d
auto t = testArray!(10, "int")(60);
```

As the template parameter being part of the constructor would only change the constructor (and can't change anything like types outside the ctor) it doesn't have any limitations and if you define it in the same module as the struct you can also access the private members.

Reply via email to