Linker Error with Template Function

Kyle Ingraham kyle at kyleingraham.com
Tue Sep 13 03:00:17 UTC 2022


On Tuesday, 13 September 2022 at 01:46:14 UTC, Paul Backus wrote:
> On Tuesday, 13 September 2022 at 00:57:58 UTC, Kyle Ingraham 
> wrote:
>> I am writing a library where I would like to be able to store 
>> instances of a type of class to an associative array for later 
>> usage. Each class stored has to implement a function as part 
>> of the required interface. The argument given is always the 
>> same type but the return value should be flexible. I solved 
>> this with an interface:
>>
>> ```d
>> interface PathConverter
>> {
>>     T toD(T)(const string value) @safe;
>> }
>> ```
>
> https://dlang.org/spec/template.html#limitations
>
>> Templates cannot be used to add non-static fields or virtual 
>> functions to classes or interfaces.
>
> You *should* get an error from the compiler for trying to do 
> this, instead of just a linker error somewhere else down the 
> line, but either way it's not going to work. You'll have to 
> find another solution.

Thanks for the spec help Paul. I must've skirted around the 
compiler somehow. This is a minimal example that triggers the 
linker error:

```d
interface PathConverter
{
     T toD(T)(string value);
}

class NumberConverter(T) : PathConverter
{
     T toD(T)(string value)
     {
         import std.conv : to;

         return to!T(value);
     }
}

alias IntConverter = NumberConverter!int;

void main()
{
     PathConverter[string] allConverters;
     allConverters["int"] = new IntConverter;
     int converted = allConverters["int"].toD!int("9");
}
```

Any suggestions for being able to call one function for any 
instance given but maintain flexible return types?


More information about the Digitalmars-d-learn mailing list