How do I initialize a templated constructor?

rempas rempas at tutanota.com
Mon Aug 8 07:37:16 UTC 2022


On Monday, 8 August 2022 at 06:58:42 UTC, bauss wrote:
>
> ```
> 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);
> ```

Thank you for all the great info! Unfortunately, while there is 
no problem in this example, this will
not do for my real code as I need to have the argument in the 
constructor. Alternative, I have to
change the design of the program completely....


More information about the Digitalmars-d-learn mailing list