Click here to Skip to main content
15,891,633 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this function:
C++
void Add(T item) { // template <class T> is assigned at class level
  array.push_back(item);
} //THIS WORKS FINE

void AddRange(T* collection) {
  for (int i = 0; i < (sizeof(collection)/sizeof(collection[0])); i++) {
    Add(collection[i];
  }
} //THIS DOES NOT WORK

List<int> intList = List<int>();
int arr[] = { 1, 2, 34, 5 };
intList.AddRange(arr);
PrintI(intList[0]); //prints "1". Like it should
PrintI(intList[1]); //prints random numbers, examples include "16318656" and "15925440"


But, however this works:
C++
for (int i = 0; i < (sizeof(arr)/sizeof(arr[0])); i++) {
  intList.Add(arr[i]);
}

I assume it has something to do with the template <class t="">, how do i fix it. And how does the template screw it up?

What I have tried:

I have tried many things, obviously i tried moving the code to the main function which works, and many things. Also the main function is in main.cpp, while the rest is in arrayFuncs.h
Posted
Updated 21-Nov-21 9:23am

1 solution

The problem is in this line :
C++
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.
C++
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.
C++
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[^]
 
Share this answer
 
Comments
CPallini 21-Nov-21 16:57pm    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900