Use template parameter as constructor parameter : template parameter « template « C++ Tutorial






#include <iostream.h>
#include <math.h>

template <class T>

class Rect
{  
       T x1,x2,y1,y2;
public:
    Rect(T a,T b,T c,T d)  {
        x1=a;
        y1=b;
        x2=c;
        y2=d;
    }
    T Area();
    T Distance();
};

template <class T>
T Rect<T>::Area()
{      return (x1-x2)*(y1-y2);}

template <class T>
T Rect<T>::Distance(){ 
    return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}

main()
{
   Rect<int> p1(2.5,3.5,5.5,7);
   cout <<p1.Area()<<endl;
   cout <<p1.Distance()<<endl;
   Rect <float> p2(2.5,3.5,5.5,7.0);
   cout <<p2.Area()<<endl;
   cout <<p2.Distance()<<endl;
   return 0;
}
12
5
10.5
4.60977








13.4.template parameter
13.4.1.Demonstrate non-type template arguments
13.4.2.Default template arguments
13.4.3.primary template: yield second or third argument depending on first argument
13.4.4.primary template to compute sqrt(N) via iteration and partial specialization to end the iteration
13.4.5.Sqrt: primary template: yield second or third argument depending on first argument
13.4.6.Loop with generic parameter
13.4.7.Define implicit_cast
13.4.8.template function for generic parameter and pointer to generic parameter
13.4.9.Nested template type
13.4.10.Use template parameter as constructor parameter