Warning

# 4 - Šablony funkcí a tříd

## Šablona funkce

#include <iostream>

template  T mymax (T a, T b)
{
return (a > b) ? a : b;
}

int main ()
{
std::cout << mymax(10,3) << std::endl;
std::cout << mymax(2.0, 3.14) << std::endl;
std::cout << mymax('a', 'e') << std::endl;
// co se porovnava u stringu?
std::cout << mymax("a", "e") << std::endl;

return 0;
}

## Šablona třídy - zásobník

template <class T> Stack
{
private:
T* items;
int stackPointer;

public:
Stack(int max = 100)
{
items = new T[max];
stackPointer = 0;
}

void Push(T x)
{
items[stackPointer++] = x;
}

T Pop()
{
return items[--stackPointer];
}
};

## Šablona třídy - pole

#include <iostream>

using namespace std;

template <class T>
class Array {
T * array_data;
int array_size;
public:
Array (int size = 10);
~Array ();
Array (const Array<T> & src);
int size() const { return array_size; }
Array<T> & operator = (const Array<T> & src);
T & operator [] (int idx);
const T & operator [] (int idx) const;
};

template <class T>
Array<T>::Array (int size) {
array_size = size;
array_data = new T [array_size];
}

template <class T>
Array<T>::~Array ( ) {
delete [] array_data;
}

template <class T>
Array<T>::Array (const Array<T> & src ) {
array_size = src.array_size;
array_data = new T[array_size];
for (int i = 0; i < array_size; i++)
array_data[i] = src.array_data[i];
}

template <class T>
Array<T> & Array<T>::operator = (const Array<T> & src) {
if (this != &src) {
delete [] array_data;
array_size = src.array_size;
array_data = new T[array_size];
for (int i = 0; i < array_size; i++)
array_data[i] = src.array_data[i];
}
return *this;
}

template <class T>
T & Array<T>::operator [] (int idx) {
if (idx < 0 || idx >= array_size)
throw "Spatny index";
return array_data[idx];
}

template <class T>
const T & Array<T>::operator [] (int idx) const {
if (idx < 0 || idx >= array_size)
throw "Spatny index";
return array_data[idx];
}

template <class T>
ostream & operator<< (ostream & o, const Array<T> & x) {
for (int i = 0; i < x.size (); i++)
o << x[i] << ' ';
return o;
}

int main () {
Array <int> a (5);

for (int i = 0; i < a.size (); i++) a[i] = i;
cout << "array a: " << a << endl; // [0 1 2 3 4]

Array<int> b = a;
b[1] = 10;
cout << "array a: " << a << endl; // [0 1 2 3 4]
cout << "array b: " << b << endl; // [0 10 2 3 4]

Array<double> c (5);
c[1] = 20;
cout << "array c: " << c << endl; // [? 20 ? ? ?]

Array<double> d = c;
d[2] = 30;
cout << "array d: " << d << endl; // [? 20 30 ? ?]

return 0;
}