template in c++
// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
template in c++
// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
template function in C++
// template specialization
#include <iostream>
using namespace std;
// class template:
template <class T>
class mycontainer {
T element;
public:
mycontainer (T arg) {element=arg;}
T increase () {return ++element;}
};
// class template specialization:
template <>
class mycontainer <char> {
char element;
public:
mycontainer (char arg) {element=arg;}
char uppercase ()
{
if ((element>='a')&&(element<='z'))
element+='A'-'a';
return element;
}
};
int main () {
mycontainer<int> myint (7);
mycontainer<char> mychar ('j');
cout << myint.increase() << endl;
cout << mychar.uppercase() << endl;
return 0;
}
c++ template
#include <bits/stdc++.h>
using namespace std;
template <class T>
class Vector{
public:
T *arr;
T size;
Vector(int size){
this->size = size;
arr = new T[size];
}
T 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] = 1;
v1.arr[1] = 2;
v1.arr[2] = 3;
Vector<int> v2(3);
v2.arr[0] = 4;
v2.arr[1] = 5;
v2.arr[2] = 6;
int a = v1.dotProduct(v2);
cout<<a<<endl;
Vector<float> v3(3);
v3.arr[2] = 3.2;
v3.arr[0] = 1.2;
v3.arr[1] = 2.2;
Vector<float> v4(3);
v4.arr[0] = 4.4;
v4.arr[1] = 5.4;
v4.arr[2] = 6.4;
float a1 = v3.dotProduct(v4);
cout<<a1<<endl;
return 0;
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us