C++ Template basic example
Here I am saving my source code so that I can revise my old topics and I will be able to see my progress that how I am increasing my capacity day by day,,,.
I know that its a example that harry bhai took in his course;
but I have coded it after watching his video.(don't spam);
#include<iostream>
using namespace std;
template <class T>
class vector{
public:
T *arr;
int size;
vector(int m)
{
size = m;
arr = new T[size];
}
int dotProduct(vector &v){
T d =0;
for(int i = 0; i<size; i++){
d+= this->arr[i]*v.arr[i];
}
return d;
}
};
int main(){
vector<int> v1(3);
v1.arr[0] = 4;
v1.arr[1] = 3;
v1.arr[2] = 1;
vector<int> v2(3);
v2.arr[0] = 1;
v2.arr[1] = 0;
v2.arr[2] = 1;
int a = v1.dotProduct(v2);
cout<<a<<endl;
return 0;
}
//without writing the template and we can use only int numbers so we use to make,
//template so that I can use any type of data types like float double and long double as well.
// Here I thought my own example;//Here I may have made spelling mistake please ignore it kindly
//please undestand my feel;
#include<iostream>
using namespace std;
template <class T = int, class T1 = int>
class claculator{
private:
T a;
T1 b;
public:
void add(T x, T1 y){
a = x;
b = y;
cout<<"The sum is "<<a+b<<endl;
}
void multiply(T, T1);
};
template <class T, class T1>
void claculator<T, T1>:: multiply(T x, T1 y){
a = x;
b = y;
printf("The multiplication is ");
cout<<a*b;
};
int main(){
claculator<>c1;
c1.add(12, 34);
c1.multiply(2, 4);
return 0;
}
0 Comments