template in c++
template <typename T>
void Swap(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
template in c++
template <typename T>
void Swap(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
template in c++
// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
what is template in c++
A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by keyword ‘class’.
templates c++
template < typename T >
inline T max ( T a , T b ) {
return a > b ? a : b ;
}
int main ()
{
// Isso chamará max <int> por dedução implícita do argumento.
std :: cout << max ( 3 , 7 ) << std :: endl ;
// Isso chamará max <double> por dedução implícita do argumento.
std :: cout << max ( 3.0 , 7.0 ) << std :: endl ;
// Isso depende do compilador. Alguns compiladores lidam com isso definindo uma
função de
modelo // como double max <double> (double a, double b) ;, enquanto em alguns compiladores // precisamos convertê-lo explicitamente, como std :: cout << max <double> (3,7,0);
std :: cout << max ( 3 , 7.0 ) << std :: endl ;
std :: cout << max < double > ( 3 , 7.0 ) << std :: endl ;
return 0 ;
}
c++ template
// class templates
#include <iostream>
using namespace std;
template <class T>
class mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
};
template <class T>
T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
int main () {
mypair <int> myobject (100, 75);
cout << myobject.getmax();
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