/* Example of a template that sums up an array operator + must be defined for the type T must have a constructor that takes a zero argument T must have a constructor that takes no arguments T must have operator= or the default copy must be ok */ #include template T sumstuff( T *thing, int num ) { T result = (T)0; for(int i=0;i class Vec { public: T x[2]; Vec(void) { x[0] = x[1] = 0; } Vec(T z) { x[0] = z; x[1] = z; } Vec operator+(const Vec &b) { Vec c; c.x[0] = this->x[0] + b.x[0]; c.x[1] = this->x[1] + b.x[1]; return( c ); } }; int main(int argc, char *argv[]) { int istuff[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; float fstuff[10] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0}; int iresult = sumstuff( istuff, 10 ); printf("result %d\n", iresult); float fresult = sumstuff( fstuff, 10 ); printf("result %.2f\n", fresult); Vec vstuff[10]; for(int i=0;i<10;i++) { vstuff[i].x[0] = i; vstuff[i].x[1] = i+1; } Vec vresult = sumstuff( vstuff, 10 ); printf("result %.2f %.2f\n", vresult.x[0], vresult.x[1]); Vec vistuff[10]; for(int i=0;i<10;i++) { vistuff[i].x[0] = i; vistuff[i].x[1] = i+1; } Vec viresult = sumstuff( vistuff, 10 ); printf("result %d %d\n", viresult.x[0], viresult.x[1]); return(0); }