Skip to main content

Template in C++

 



#include <bits/stdc++.h>

using namespace std;
template <class T>   //Here T is like a data type in main function we will
                    tell compiler which type of data type it's
class doing
{
  
public:
    T *a;
    int size;
    doing(int x)
    {
        size = x;
        a = new T[size];
    }
    T dotproduct(doing v)
    {
        T s = 0;
        for (int i = 0; i < size; i++)
        {
            s += this->a[i] * v.a[i];
        }
        return s;
    }
};

int main()
{
    // doing o(3);
    // o.a[0] = 4;
    // o.a[1] = 3;
    // o.a[2] = 1;
    // doing e(3);
    // e.a[0] = 1;
    // e.a[1] = 0;
    // e.a[2] = 1;
    // int b = o.dotproduct(e);
    // cout << b << endl;

    doing <float>o(3);
    o.a[0] = 4.0;
    o.a[1] = 1.3;
    o.a[2] = 1.0;
    doing <float>e(3);
    e.a[0] = 1.5;
    e.a[1] = 0.2;
    e.a[2] = 1.6;
    float b = o.dotproduct(e);
    cout << b << endl;
    return 0;
}

















#include<bits/stdc++.h>

using namespace std;
//template <class T,class T2>           //template with multiple parameters
template <class T=int,class T2=float>  //template with default parameters
class make{
    public:
    T a;
    T2 b;
    make(T x, T2 y){
        a=x;
        b=y;
    }
    void display(){
        cout<<a<<endl<<b<<endl;
    }
};
int main()
{
    make<int,char> o(1,'m');
    o.display();
    cout<<endl;
    make<> p(1,1.2);        //default parameters
    p.display();
    return 0;
}









#include<bits/stdc++.h>

using namespace std;
template <class T, class T2>
T sum(T x , T2 y){
    T s;
    s = x+y;
    cout<<s;
    return 0;
}
int main()
{  
    cout<<"Your sum is: ";
    sum<double>(4,8);
       
    return 0;
}





Comments