#include <iostream>
/************************ Definitionen von Templates ************************/
template <typename T>
// typename ist ein Schlüsselwort, T steht für irgendeinen Typ.
// Statt typename kann auch class verwendet werden.
T max(T a, T b)
{return a>b ? a : b;}
template <typename T>
void sort2(T& a, T& b)
// T& bedeutet eine Referenz auf eine Instanz des Typs T.
{
if (a>b) // Der Operator '>' muss auf dem Typ T definiert sein.
{
T temp = a;
a = b;
b = temp;
}
}
/************************** Verwendung von Templates ************************/
int main ()
{
int i1=3, i2=5, i;
i = max(i1,i2);
// Der Compiler erzeugt die Funktion max nach obiger Schablone für int.
cout<<"max("<<i1<<","<<i2<<") = "<<i<<'\n';
cout<<"Ordnen von {"<<i1<<", "<<i2<<"}: ";
sort2(i1,i2);
// Der Compiler erzeugt die Funktion sort2 nach obiger Schablone für int.
cout<<i1<<", "<<i2<<"\n\n";
double d1=5.18, d2=3.99, d;
d = max(d1,d2);
// Der Compiler erzeugt die Funktion max nach obiger Schablone für double.
cout<<"max("<<d1<<","<<d2<<") = "<<d<<'\n';
cout<<"Ordnen von {"<<d1<<", "<<d2<<"}: ";
sort2(d1,d2);
// Der Compiler erzeugt die Funktion sort2 nach obiger Schablone für double.
cout<<d1<<", "<<d2<<"\n\n";
return 0;
}
|