c++ template code example
Example 1: c++ template function
template <class T>
void swap(T & lhs, T & rhs)
{
T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
Example 2: 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);
double f = 5.5;
double g = 42.0;
swap(f, g);
printf("f=%f, g=%f\n", f, g);
}
Example 3: 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;
}
Example 4: cpp how to create an object of template class
template class Graph<string>;
Example 5: c++ class template
#include <vector>
template <class T1, class T2, typename T3, typename T4 = int>
class MyClass
{
public:
MyClass() { }
private:
T1 data;
T2 anotherData;
T3 variable;
}
int main(int argc, char **argv)
{
std::vector<int> array(10);
MyClass<int> object();
return (0);
}
Example 6: c++ template
#include <iostream>
#include <string>
using namespace std;
int main() {
}