I need to write a container template class <T, R> where T is an object and R can be either vector<T*> or list<T*>. i need to support common operations like insert(T) size() etc…
I am holding a class member called T data to be the list or the vector. the problem is, how do i write the code so at runtime i know which operation to invoke from std::list or std::vector ?
for example, to get the fist element in the container i would have to invoke data[0] in the vector case and data.front() in lists case. should i just use typeid operator ?
if (typeid(R) == typeid(vector<T*>))
then ...
else if (typeid(R) == typeid(list<T*>))
then ...
Or is there a better way ?
You can use iterators — they are standard idioms in the STL. Use
begin()to get the iterator pointing to the beginning of the collection andend()to get the end (more precisely, the iterator pointing to the element “after” the last in the collection). You can also usepush_back()with bothlist<>andvector<>to add elements to the end of the collection,insert()to add an element to a specific position anderaseto delete an element from the collection. Check out the reference (vector, list) for more common functions.The idea is that method calls in templates are not checked until the point of instantiation (and sepcifically until the call of template functions), so the above mentioned calls will bind to the exact collection type you specified in the template