Template Klassen

Analog für Klassen Definitionen:


#include <iostream>
template < class T1, class T2>
class pair {
public:
  T1 first;
  T2 second;
  pair(const T1& x,const T2&y): first(x),second(y){}
};
int main()
{
  pair <double,int> p1(3.14,7);
  pair <int,double> p2(9,4.4);
  cout << "p1:" << p1.first << " " << p1.second << endl;
  cout << "p2:" << p2.first << " " << p2.second << endl;
};


Der Pre-Compiler erstellt:


class pair_di {
public:
  double first;
  int second;
  pair(const double & x,const int &y): first(x),second(y){}
};
class pair_id {
public:
  int first;
.
  pair_di p1(3.14,7);
  pair_id p2(9,4.4);
..



Anmerkung:

In obigem Beispiel wurde eine besonders kompakte Variante von Verzweigungen in C/C++ verwendet:


// Kurzform
 r = (x < y ? y:x); 
// entspricht
if ( x < y ) {
  r = y;
 }
else {
  r = x;
}



Generic Programming

Templates ermöglichen das sog. Generische Programmieren




GDuckeck 2019-08-01