Hello,
I downloaded a book from one of you guys that I am now reading. A code
snippet in the example wraps a template around a class. Beyond that I
really can't explain it in too much detail due to experience. I am
reading about catching and throwing exceptions and handling errors. I
have included the code so someone else could explain in greater detail
what's going on with the code. I don't know why someone would use a
template as a wrapper for a class in the first place. What do
templates do that are so special? Can't you just nest a class within a
class if you want to wrap a class? You can't put functions, unions,
enums, etc. inside a template anyway can you?
Here's the code:
#include <iostream>
#include <cstddef>
using namespace std;
// Simplified. Yours may have other arguments.
template<class T, int sz = 1> class PWrap {
T *ptr;
public:
class RangeError {}; // Exception class
PWrap() {
ptr = new T[sz];
cout << "PWrap constructor" << endl;
}
~PWrap() {
delete[] ptr;
cout << "PWrap destructor" << endl;
}
T& operator[](int i) throw(RangeError) {
if(i >= 0 && i < sz) return ptr[i];
throw RangeError();
}
};
class Cat {
public:
Cat() { cout << "Cat()" << endl; }
~Cat() { cout << "~Cat()" << endl; }
void g() {}
};
class Dog {
public:
void* operator new[](size_t) {
cout << "Allocating a Dog" << endl;
throw 47;
}
void operator delete[](void* p) {
cout << "Deallocating a Dog" << endl;
::operator delete[](p);
}
};
class UseResources {
PWrap<Cat, 3> cats;
PWrap<Dog> dog;
public:
UseResources() { cout << "UseResources()" << endl; }
~UseResources() { cout << "~UseResources()" << endl; }
void f() { cats[1].g(); }
};
int main() {
try {
UseResources ur;
} catch(int) {
cout << "inside handler" << endl;
} catch(...) {
cout << "inside catch(...)" << endl;
}
} ///:~
Thanks
KW