Template class and arrays...

Okay, so, say I have a template class which holds a pointer to a dynamically allocated array. The type of the array is determined by the template.

What I need is a way to "erase" an item from the array. Specifically, the last item (which is easier because you don't have to move around values). Say I have this function:

1
2
3
4
5
template <typename T>
void SomeClass<T>::WeirdFunction()
{
  arrayPtr[endValue] = NULL;
}


where arrayPtr is a pointer to the array and endValue is an int which holds the subscript of the array's last element.

But since I don't know the type of the array, I can't just set it to NULL or 0 (what if it's a string?). I even tried allocating a new object of type T, and assigning it to the array's item, but that failed with an access violation error.

Any ideas?
Try with T(), it is the default value of 'T' but this shouldn't work if 'T' has only constructors which need some arguments.
You should try STL containers, some have a method called 'pop_back' which removes the last element
Use a std::vector and just resize it to length - 1.
With a vector you could just use vector.erase or vector.pop_back anyway.

EDIT:
You should try STL containers, some have a method called 'pop_back' which removes the last element
Oops, didn't see that. meh.
Last edited on
Yeah, of course I would use an STL class for an actual implementation. After all, it'd be much more versatile than anything I could write up in time. The problem is that I was specifically asked to do it this way as an assignment...

And now that I think about it, I may have just had an off-by-one error on the pointer's subscript... I have another function that adds a value to the end of the array, and updates the endpoint marker, so I may have tried writing past the end of the array.

I'll try using T() when I get home. Would you just write it like:
arrayPtr[endValue] = T();

Or would I have to instantiate a temporary variable and then assign it to the array?

Thanks for the tips, guys!
If you don't need to create a new variable don't do it
T() is the only way to do what you want generically, which requires default constructibility.
Hey everyone, thanks for posting.

Turns out it was a simple off-by-one error. I had forgotten to decrement the array endValue before using it as a subscript. I changed that, and used T(), and it worked perfectly.
Thanks again!
Topic archived. No new replies allowed.