c++ template function
template <class T>
void swap(T & lhs, T & rhs)
{
T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
c++ template function
template <class T>
void swap(T & lhs, T & rhs)
{
T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
function template
template <class T>
void swap(T & lhs, T & rhs)
{
T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
void main()
{
int a = 6;
int b = 42;
swap<int>(a, b);
printf("a=%d, b=%d\n", a, b);
// Implicit template parameter deduction
double f = 5.5;
double g = 42.0;
swap(f, g);
printf("f=%f, g=%f\n", f, g);
}
/*
Output:
a=42, b=6
f=42.0, g=5.5
*/
c++ template
#include <iostream>
using namespace std;
template <typename T>
void Swap(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{
int i1 = 1, i2 = 2;
float f1 = 1.1, f2 = 2.2;
char c1 = 'a', c2 = 'b';
cout << "Before passing data to function template.\n";
cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;
Swap(i1, i2);
Swap(f1, f2);
Swap(c1, c2);
cout << "\n\nAfter passing data to function template.\n";
cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;
return 0;
}
template in c++
// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
c++ template
// function template
#include <iostream>
using namespace std;
template <class T>
T GetMax (T a, T b) {
T result;
result = (a>b)? a : b;
return (result);
}
int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax<int>(i,j);
n=GetMax<long>(l,m);
cout << k << endl;
cout << n << endl;
return 0;
}
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 ;
}
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