How do I initialize a templated constructor?

Steven Schveighoffer schveiguy at gmail.com
Mon Aug 8 13:51:23 UTC 2022


On 8/8/22 9:36 AM, Steven Schveighoffer wrote:
> On 8/8/22 1:38 AM, 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!
> 
> You cannot explicitly specify template parameters for constructors.
> 
> The only true solution is to use a factory function:
> 
> ```d
> TestArray!T testarray(string s, T)(T val) {
>     ... // code that depends on s here
>     return TestArray!T(...) // call ctor here.
> }
> ```

Just thought of another possibility:

```d
struct StringAnnotated(string s, T)
{
    T val;
}

StringAnnotated!(s, T) annotate(string s, T)(T val)
{
    return StringAnnotated!(s, T)(val);
}

struct TestArray(ulong element_n)
{
    ...
    this(T)(T val) if (isInstanceOf!(StringAnnotated, T))
    {
       ...
    }
}

// use like
TestArray!10(60.annotate!"int");
```

-Steve


More information about the Digitalmars-d-learn mailing list