Template Class

This is my first time doing templates, I'm not sure whatI'm missing

#include <iostream>
using namespace std;

// Use this file to implement the templated class SumList
// SumList is a class that stores an array of 10 elements of a templated type
//
// The constructor takes no parameters and sets all elements of the array to 0
//
// setIndex function takes an index and value
// and sets the element of the array at the given index to the given value
// (assume 0<=index<=9)
//
// sum function should return the sum off all elements in the list

const int SIZE = 10;
//*****************************************
// Implement the class SumList (including constructor, setIndex, and sum) here:


template <class T> class SumList {
private:
//m_array = SIZE;
T *m_array;


public:
SumList(int s){
SIZE = s;

m_array = new T[SIZE];
}

void setIndex(int elem, T val){
m_array[elem] = val;
}

T sum(){
int result = 0;

for(int i=0; i<SIZE; i++){
result += m_array[i];
}
return result;
}
};

______________________________


int main() {
SumList<int> intList; // Uses template class as a list of 10 ints
SumList<float> floatList; // Uses template class as a list of 10 floats
SumList<unsigned int> uintList;// Uses template class as a list of 10 unsigned ints

// Tests SumList<int>
int intVals[] = {0,1,2,3,4,-5,6,7,8,9}; //An array of ints
for (int i=0; i<10; i++) {
intList.setIndex(i, intVals[i]); //Adds ints to our intList
}
cout << "int results (35 expected):" << endl;
cout << intList.sum() << endl;

// Tests SumList<float>
// initial list should be all 0.0
cout << endl << "float results: (0 expected):" << endl;
cout << floatList.sum() << endl;
float floatVals[] = {0,0.5,1,1.5,2,2.5,3,3.5,4,-4.5};
for (int i=0; i<10; i++) {
floatList.setIndex(i, floatVals[i]);
}
cout << endl << "float results: (13.5 expected):" << endl;
cout << floatList.sum() << endl;

// Test SumList<unsigned int>
unsigned int uintVals[] = {1000,234556,0,78,2333,3,0,0,0,0};
for (int i=0; i<10; i++) {
uintList.setIndex(i, uintVals[i]);
}
cout << endl << "unsigned int results: (237970 expected):" << endl;
cout << uintList.sum() << endl;

return 0;
}
Last edited on
1
2
3
for
m_array = new T[SIZE];
}


That's not valid code.
Last edited on
Yes, It still doesn't work. I was trying to see if I should have a loop there
SumList<int> intList;

This is an attempt to use the template constructor SumList(). No such constructor exists.

You do have this one, though: SumList(int s)
Topic archived. No new replies allowed.