Tuesday, October 25, 2016

Dot Product Of Vectors With Template Class

Tags

By using Template Class We Can do Generic Programming that is we can avoid the writing of same code for different datatypes.
Following Program Illustrate This Concept:
#include<iostream>
using namespace std;
template<class T>
class vector
{ T v[3];
public:
vector()
{ cout<<"Enter The Components of vector\n";
for(int i=0;i<3;i++)
cin>>v[i];
}
T operator*(vector &b)
{ T sum=0;
for(int i=0;i<3;i++)
sum+=v[i]*b.v[i];
return sum;
}
void display()
{ cout<<"Components of Vector Are ";
for(int i=0;i<3;i++)
cout<<v[i]<<"\t";
cout<<"\n";
}
};
main()
{ vector<typename>v1,v2;   //type name any type for which we want to do product
v1.display();
v2.display();
cout<<"V1*V2="<<v1*v2;
}

Output: