====== Templates κλάσεων ====== Σε αναλογία με τα templates συναρτήσεων μπορούμε να κατασκευάσουμε κλάσεις που να λαμβάνουν ως παράμετρο ένα ή περισσότερους τύπους δεδομένων. Στο παρακάτω παράδειγμα, έχουμε την κλάση **Box** η οποία είναι παραμετρική. #ifndef _BOX_HPP_ #define _BOX_HPP_ template class Box { T e; public: Box(T e); T get() const; void set(T e); template friend std::ostream& operator<<(std::ostream& out, const Box& t); }; template Box::Box(T e) { this->e = e; } template T Box::get() const { return e; } template void Box::set(T e) { this->e = e; } template std::ostream& operator<<(std::ostream& out, const Box& t) { out << t.get(); return out; } #endif H παραπάνω κλάση μπορεί να παράγει διαφορετικούς τύπους δεδομένων, ανάλογα με τον τύπο **T**. Στο παρακάτω παράδειγμα έχουμε ένα μία κλάση **Box**, μία κλάση **Box** και μία κλάση **Box**. #include #include "Box.hpp" #include "Student.hpp" using namespace std; int main() { Box b(15); Box d(4.23); Student kate = {"Kate", 1234}; Box studentBox(kate); Student katherine = studentBox.get(); katherine.setName("Katherine"); cout << "--- Printing Values ---" << endl; cout << kate << endl; cout << katherine << endl; cout << studentBox.get() << endl; cout << "--- Destroying objects ---" << endl; } ===== Ένα πιο σύνθετο παράδειγμα ===== Ας υποθέσουμε ότι θέλουμε να κατασκευάσουμε ένα στατικό πίνακα (συγκεκριμένης χωρητικότητας) για την αποθήκευση πληροφορίας. Σε αναλογία με την κλάση **Box<Τ>** θέλουμε να φτιάξουμε ένα πίνακα στον οποίο να μπορούμε να αποθηκεύσουμε διαφορετικούς τύπους δεδομένων. Η παρακάτω κλάση **Array** περιέχει ένα στατικό πίνακα δεδομένων μεγέθους //size//: #ifndef __ARRAY_H__ #define __ARRAY_H__ #include #include #include template class Array { T array[size]; public: Array(); Array(const Array& a); void set(T e, int index); T get(int index) const; void rmv(int index); Array& operator=(Array& a); T& operator[](int index); template friend std::ostream &operator<<(std::ostream& out, const Array& t); }; template Array::Array() { // empty } template Array::Array(const Array& a) { for(int i=0; i void Array::set(T e, int index) { assert(index>=0 && index T Array::get(int index) const { assert(index>=0 && index void Array::rmv(int index) { assert(index>=0 && index Array& Array::operator=(Array& a) { for(int i=0; i T& Array::operator[](int index) { assert(index>=0 && index std::ostream &operator<<(std::ostream& out, const Array& t) { for(int i=0; i #include "Array.hpp" #include "Student.hpp" #define ARRAY_SIZE 10 using namespace std; int main() { Array a; for(int i=0; i b(a); cout << "--- Printing b ---\n"; cout << b << endl; Array sts; sts[0] = Student("Kate", 12345); sts[1] = Student("Nick", 12346); sts[2] = Student("Mary", 12347); sts[3] = Student("Susan", 12348); cout << "--- Printing sts ---\n"; cout << sts << endl; }