The problem is in this line :
for (int i = 0; i < (sizeof(collection)/sizeof(collection[0])); i++)
because it will iterate only once. Add an output statement there to see for yourself how many items are added.
void AddRange(T* collection)
{
for (int i = 0; i < (sizeof(collection)/sizeof(collection[0])); i++)
{
Add( collection[i] );
std::cout << "added item " << i + 1 << std::endl;
}
}
The reason the second one works is that
sizeof(arr)
gives the result you expect because the compiler knows it is an array.
collection
is just a pointer so in the previous one and not an array. If you pass the count into the
Add
method then it can work as you expect.
void AddRange( T* collection, size_t count )
{
for( size_t i = 0; i < count; i++ )
{
Add( collection[i] );
std::cout << "added item " << i + 1 << std::endl;
}
}
Visual C++ has a built in macro for that expression :
_countof Macro | Microsoft Docs[
^]