this T / variadic template and interfaces

Simen Kjærås simen.kjaras at gmail.com
Mon Oct 26 11:48:48 UTC 2020


On Monday, 26 October 2020 at 11:14:47 UTC, frame wrote:
> Did not find this topic:
>
> I have an interface and some wrapper classes that use it. The 
> wrapper's methods should accept variadic arguments. The runtime 
> should only work with the interface, trying casting to a 
> wrapper is not an option, because it's a plugin design.
>
> - defining a variadic template in wrapper does not work, 
> because we are working with the interface only and compiler 
> complains method is not callable with argument X
>
> - defining a variadic template without body in interface causes 
> linker errors, which makes sense somehow
>
> - defining a variadic template with body in interface could 
> work if the compiler would get the right "this" type but sadly, 
> "this" refers to interface and also "this T" refers to 
> interface too.
>
> Is there any way to get this working? I know, I could use a 
> known object to feed the arguments and use that instead - but I 
> want to keep things simple as possible.

Templates can't be virtual, so even if they can be defined in an 
interface, you can't override them in a class that implements 
said interface - the implementation needs to be in the interface 
itself.

This makes sense if you consider that the user of the interface 
has no knowledge of the types that implement it, and vice versa: 
the implementing class has no idea which instantiations to make, 
and the user has no idea which implementing classes to create 
instantiations for. Templates require that the user have full 
knowledge of the templates to be instantiated.

There are some workarounds of sorts, but they depend heavily on 
what you're trying to achieve. Can you use an array of 
std.variant.Variant, for instance?

--
   Simen


More information about the Digitalmars-d-learn mailing list