How Different Are Templates from Generics

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Oct 11 18:19:53 UTC 2019


On Friday, October 11, 2019 12:09:20 PM MDT Just Dave via Digitalmars-d-
learn wrote:
> Thanks for the thorough explanation. Most of that is how I was
> thinking it worked. However, that leaves me perplexed. If
> templates just generate code then how come:
>
> Wouldnt..
>
>      class SomeClass(T) : ISomeInterface!T
>
> and..
>
>      class SomeOtherClass(T) : ISomeInterface!T
>
> ...generate two different interfaces? Two interfaces that do the
> same thing, but two interfaces nonetheless? I assume each type in
> D has some form of type id underlying everything, which wouldn't
> that make the follow:
>
>      if (instance1 is ISomeInterface<int>)
>      {
>          Console.WriteLine("Instance1 is interface!");
>      }
>
> fail? Or is there some extra magic that is making it work with my
> experiments?

You get a different template instantiation for each set of template
arguments. So, if you have ISomeInterface!int, and you use
ISomeinterface!int somewhere else, because they're both instantiating
ISomeInterface with the same set of template arguments, you only get one
instantiation. So,

    class SomeClass : ISomeInterface!int

and

    class SomeOtherClass : ISomeInterface!int

would both be implementing the exact same interface. And if you then have

    class SomeClass(T) : ISomeInterface!T

and

    class SomeOtherClass(T) : ISomeInterface!T

then SomeClass!int and SomeOtherClass!int would both be implementing the
same interface, because in both cases, it would be ISomeInterface!int.
SomeClass!int and SomeOtherClass!float would not be implementing the same
interface, because it would be ISomeInterface!int and ISomeInterface!float,
but ISomeInterface!int doesn't result in multiple instantiations even if
it's used in different parts of the code.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list