We have just been introduced to generics and templates in my comp sci class.
I have been asked to create a generic container class that supports storage and retrieval of any data type.
I have all of my functions working okay, except when it comes to resize my array. I have the call for resize inside my insert function:
template< typename T >
void Container< T >::insert( T magic)
{
if (index == size)
{
resize();
}
containerPtr[index] = magic;
index++;
}
The size variable is the size of the array and the index is the next insert location.
and here is my resize function:
template< typename T >
void Container< T >::resize()
{
int doubSize = size * 2;
Container< T > temp(doubSize);
for (int i = 0; i < size; i++)
{
temp[i] = containerPtr[i]; // error 1 here
}
*containerPtr = temp; // error 2 here
size = doubSize;
}
My overloaded =
template< typename T >
const T Container< T >::operator=(const T& rhs)
{
if(this == &rhs)
{
return *this;
}
return *rhs;
}
I receive the following errors when I try to compile:
1: error C2676: binary '[': 'Container<T>' does not define this operator or a conversion to a type acceptable to the predefined operator
2: error C2679: binary '=': no operator found which takes a right-hand operand of type 'Container<T>' (or there is no acceptable conversion)
I am not sure where I am going wrong here…
Is the more important error, it states that what ever you believe the types to be on
this line of code is incorrect. It is impossible to assign a
container<T>to a T value which is what you are trying to do. After you change temp to a pointer to a dynamically allocated array of T that is of the correct size(and remove the pointer deref on the assignment) the other error will go away on its own. Note you will also want to fix the memory leak where you forget to delete the previous array.