Ref. to my last post and sellibitze’s comment to that post on passing array by ref rather than by value, why is it that when I’m passing array by value compiler can deduce arguments but it won’t do it if I pass it by value?
template<class T,int row, int col>
void invert(T (&a)[row][col]) //NOTE AMPERSAND
in main with declaration above I can call:
int main(int argc, char* argv[])
{
invert(a);//HERE ARGUMETS ARE AUTOMATICALLY DEDUCED
}
but without ampersand I would have to call it like so:
int main(int argc, char* argv[])
{
invert<int,3,4>(a);
}
@Paul So just to make it clear when I’m declaring fnc:
void f(int a[]);//I'm passing a pointer
but when I’m declaring:
void f(int &a[]);//I'm passing a ref?
Do I understand this correctly now?
That’s because when you pass an array “by value” it decays to a pointer. That is, you are in fact passing a pointer to the first element without any size information.
When you have a signature like this:
then the value 10 is completely ignored and you can pass arrays of ints of any size to it. It is exactly the same as
or
As you can see the size information is not preserved, and therefore it cannot be used to deduce the size of the array.
With a two-dimensional array, the first dimension decays. For example: an array of 10 arrays of 20 integers (
int arr[10][20]) decays to a pointer to arrays of 20 integers (int (*arr)[20]) etc, so the value 10 cannot be deduced but the size of the second dimension (20) is preserved an can be deduced.When you pass something by reference, the type is preserved, the arrays don’t decay and all the size information will remain available.