#include #include // Beispiel für Templates, Operatorüberladung und Ausnahmen using std::cout; using std::endl; using std::ostream; using std::runtime_error; // Template mit Standardwerten/-typen template class Array { public: Array() : arr() {} T& operator [](unsigned i) { if (i >= N) { throw std::runtime_error("out of range"); } return arr[i]; } T const& operator [](unsigned i) const { return const_cast(*this)[i]; } private: T arr[N]; }; /* Überladener Operator ist ein Template, damit er für beliebige Array * verwendet werden kann */ template ostream& operator <<(ostream& o, Array const& a) { char sep = '('; for (unsigned i = 0; i != N; ++i) { o << sep << a[i]; sep = ','; } o << ')'; } int main() { try { Array<> a; a[10] = 23; Array<> const& b = a; cout << b << endl; Array, 5> c; cout << c << endl; } catch (std::runtime_error const& e) { std::cerr << "error: " << e.what() << std::endl; } catch (...) { std::cerr << "an error occurred" << endl; } }