Giant template - changing types everywhere

Steven Schveighoffer schveiguy at gmail.com
Fri Jul 14 14:15:29 UTC 2023


On 7/14/23 1:51 AM, Cecil Ward wrote:
> On Friday, 14 July 2023 at 05:09:58 UTC, Cecil Ward wrote:
>> On Friday, 14 July 2023 at 05:05:27 UTC, Cecil Ward wrote:
>>> On Friday, 14 July 2023 at 05:03:31 UTC, Cecil Ward wrote:
>>>>
>>>> The way I can see it going is a giant template encompassing pretty 
>>>> much the whole file. Does that mean that the caller who calls my one 
>>>> public function does so by passing the type dchar or wchar ? And 
>>>> then we generate the strings from that. It might be rather more 
>>>> natural for the caller to pass one of the string types into the 
>>>> template. That’s where I get rather more confused, say caller calls
>>>>
>>>> Transform(dstring)(dstring str)
>>>>
>>>> or can they just do Transform( "str"d ) and it would work out that 
>>>> the type is immutable dchar[] ?
>>>
>>> Perhaps I should just make up a small example file with two functions 
>>> in it to see if I can get the syntax right?
>>
>> If I wrap the whole thing with a template declaration of the xchar 
>> type, then can I get away with no changes to the individual function 
>> definitions?
> 
> I tried it, wrapped the whole thing in a template definition and it 
> compiled, but then my test file which calls Transform( someDString ) 
> failed to compile with errors saying it couldn’t find the definition of 
> Transform in the other module, which is or was public. It’s as if it is 
> no longer public because it’s now inside the template.

So templates don't automatically instantiate, you have to specify them. 
And then if your function is inside the template, to access it, you will 
need to do:

```d
GiantTemplate!dstring.Transform(str);
```

But this is not a usual way of creating API. Instead, you should 
template individual functions on the string type.

Depending on what you are doing, you can use:

```d
T Transform(T)(T val)
T[] Transform(T)(T[] val)
```

The first will cover cases where you have custom string types that 
aren't arrays, the second will just capture the array type, and ensures 
that the parameter/return is an array.

When you make template functions like this, a feature of D called 
Implicit Function Template Instantiation (IFTI) will automatically 
instantiate the template for you, so you don't have to specify the 
template parameters.

You just call `Transform(str)` and it works. With the wrapping template 
solution, this is not available -- you must explicitly instantiate the 
wrapper.

If you are having problems, it is nearly impossible to diagnose without 
some actual code to look at.

-Steve


More information about the Digitalmars-d-learn mailing list