title: C++ style templates in C#, possible in any way?
body: <p>I want to have 2d vector classes for every primitive type.</p>
  
  <p>Right now, to assure the best runtime performance and be able to use many utility functions, I need to have a separate class for every primitive (Vector2Int, Vector2Float, Vector2Long, etc).</p>
  
  <p>It's just a lot of copy-pasting, and if I have to make a change I have to remember to do it in every class and in every utility function.</p>
  
  <p>Is there anything that lets me write something like C++ templates (or is there any way I can create it)?</p>
  
  <p>I created a little concept to show you how this would work:</p>
  
  <pre><code>// compile is a keyword I just invented for compile-time generics/templates
  
  class Vector2&lt;T&gt; compile T : int, float, double, long, string
  {
      public T X { get; set; }
      public T Y { get; set; }
  
      public T GetLength() 
      {
          return Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2));
      }
  }
  
  // during compilation, code will be automatically generated
  // as if someone manually replaced T with the types specified after "compile T : "
  /*
      VALID EXAMPLE (no compilation errors):
  
      autogenerated class Vector2&lt;int&gt;
      {
          public int X { get; set; }
          public int Y { get; set; }
  
          public int GetLength() 
          {
              return Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2));
          }
      }
  
  
  
      UNVALID EXAMPLE (build failed, compilation errors):
  
      autogenerated class Vector2&lt;string&gt;
      {
          public string { get; set; } // ok
          public string { get; set; } // ok
  
          public string GetLength() 
          {
              return Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2)); // error! string cannot be used with Math.Pow()
                                               // and Math.Sqrt doesn't accept string type
          }
      }
  */
  </code></pre>
  
  <p>Is there some clever way to implement this, or is this completely impossible?</p>
  
  <hr>
  
  <p>Sorry for not being very clear, but let me explain what the problem is.</p>
  
  <p>Consider using normal C# generics. The GetLength() method wouldn't compile, because all the types I want to use (int, float, double, long) would require to share an interface which Math.Pow() should accept as a parameter.</p>
  
  <p>Literally substituting the "T" token with the type names would solve this problem, increase flexibility, reach hand-written code performance and speed up development.</p>
  
  <hr>
  
  <p>I made my own template generator, which generates C# code by writing C# code :) 
  <a href="http://www.youtube.com/watch?v=Uz868MuVvTY">http://www.youtube.com/watch?v=Uz868MuVvTY</a></p>