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!

```
this(string type)(ulong number) {
```

You cannot do this.

Instead your type should look like this:

First let's change it up a little bit.

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

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

Now the above will still not work because you do `typeof(type)` which will always yield string because type is as string and also the typeof() is not needed in this case and will actually yield an error.

If it must be a string then you can do it like this:

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

  this(ulong number) {
    mixin("alias T = " ~ type ~ ";");
    pragma(msg, "The type is: " ~ T.stringof);
  }
}
```

However the ideal implementation is probably this:

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

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

To instantiate it you simply do:

```
TestArray!(10, "int") val = TestArray!(10, "int")(100);
```

Or

```
TestArray!(10, int) val = TestArray!(10, int)(100);
```

I will recommend an alias to make it easier:

```
alias IntTestArray = TestArray!(10, int);

...

IntTestArray val = IntTestArray(100);
```

Reply via email to