How Different Are Templates from Generics
    Just Dave 
    abcdef at 1234.com
       
    Fri Oct 11 14:43:49 UTC 2019
    
    
  
I come from both a C++ and C# background. Those have been the 
primary languages I have used. In C# you can do something like 
this:
     public interface ISomeInterface<T>
     {
          T Value { get; }
     }
     public class SomeClass<T> : ISomeInterface<T>
     {
          T Value { get; set; }
     }
     public class SomeOtherClass<T> : ISomeInterface<T>
     {
         T Value { get; set; }
     }
     public static class Example
     {
         public static void Foo()
         {
             var instance1 = new SomeClass<int>(){ Value = 4; };
             var instance2 = new SomeClass<int>(){ Value = 2; };
             if (instance1 is ISomeInterface<int>)
             {
                 Console.WriteLine("Instance1 is interface!");
             }
             if (instance2 is ISomeInterface<int>)
             {
                 Console.WriteLine("Instance2 is interface!");
             }
         }
     }
Expected output is both WriteLines get hit:
     Instance1 is interface!
     Instance2 is interface!
So now the 'D' version:
     interface ISomeInterface(T)
     {
  	T getValue();
     }
     class SomeClass(T) : ISomeInterface!T
     {
     private:
	T t;
     public:
	this(T t)
	{
         this.t = t;
	}
	T getValue()
	{
        return t;
	}
     }
     class SomeOtherClass(T) : ISomeInterface!T
     {
     private:
	T t;
     public:
	this(T t)
	{
         this.t = t;
	}
	T getValue()
	{
		return t;
	}
     }
...which seems to work the same way with preliminary testing. I 
guess my question is...templates are different than generics, but 
can I feel confident continuing forward with such a design in D 
and expect this more or less to behave as I would expect in C#? 
Or are there lots of caveats I should be aware of?
    
    
More information about the Digitalmars-d-learn
mailing list