Some may or may not know that you can get the size of an array argument to a function using this code:
template<typename DataType, size_t SIZE>
void SortingAlgorithm(DataType (&array)[SIZE])
{
...
return;
}
where SIZE can be used to represent the number of elements in the array, allowing the, programmer using your function to pass the array as an argument without explicitly passing the length. For example, the programmer can do this:
SortingAlgorithm( arrayToBeSorted ); //the length is not passed here, which is fine
For Algorithms that can be implemented relatively easily in an iterative style, this is fine. But I've tried to do this with other algorithms that are recursive. The code for each one might look something like this:
template<typename DataType, size_t SIZE>
void SortingAlgorithm(DataType (&array)[SIZE])
{
DataType newArray[SIZE];
memcpy(newArray,array, SIZE); //copy to a new array
SortingAlgorithm( newArray );
...
return;
}
But this throws an error every time saying that the program expects a different argument type, type conversion has failed, and shows an attempt to typecast the SIZE specifier for the newArray array multiple times, and the program fails. It does not however spit out these errors if I use an actual value to define the size of newArray before making the recursive call, like this:
DataType newArray[10]; //arbitrary number, but the compiler accepts this.
Why is it that a variable sized array causes an error? Also is there anyway to implement a recursive algorithm that accepts an array as input but does not require the length of the array as an argument because It can determine the length of the array each time within the function call?
SortingAlgorithm<DataType, SIZE>( newArray );work?SizeGenericSortingAlgorithm(array, SIZE), calling atemplate<typename DataType> void SizeGenericSortingAlgorithm(DataType *array, size_t size).