Given:
class Point {
int x;
int y;
public:
void dump() {
cout << "x: " << x << "y: " << y << endl;
}
int getX() { return x; }
}
I want to change it to use doubles, I can do it but it requires changes to the two data members and the return type of getX.
Deriving a new class would work, but you'd have to recode everything, so there's no polymorphisim and there's lots of duplicated code (with only types changed).
Templates look like the solution:
template <class T>
class Point {
T x;
T y;
public:
void dump() {
cout << "x: " << x << "y: " << y << endl;
}
T getX() { return x; }
}
Now I can specialize for whatever type I'd like without having to change code.
But, if I want to add another variable (3d points) now I have to code another class. dump() needs to change also.
Also, if I want to be able to have a general tuple of any 3 types, I'd have to add another template parameter. It's not possible to have a variable arg template without additional code.
/msg Excedrin on efnet or mail answers to sic at tch.org