I am trying to pass 2D arrays of arbitrary size to a function. The code that i have tried is as follows:
#include <iostream>
void func(int (&arr)[5][6])
{
std::cout<<"func called"<<std::endl;
}
int main()
{
int arr[5][6];
func(arr);
return 0;
}
As you can see the func is correctly called. But i want to pass a 2D array of any size. In the current example, we can only pass int [5][6].
PS: I know i can also use vector but i want to know if there is a way to do this with array. For example, i should be able to write:
int arr2[10][15];
func(arr2);//this should work
CodePudding user response:
You could do this using templates. In particular, using nontype template parameters as shown below:
#include <iostream>
//make func a function template
template<std::size_t N, std::size_t M>
void func(int (&arr)[N][M])
{
std::cout<<"func called with: "<<N<<" rows and "<<M<<" columns"<<std::endl;
}
int main()
{
int arr2[10][15];
func(arr2);
return 0;
}
In the above example N and M are called nontype template parameters.
Using templates we can even make the type of elements in the array arbitrary, as shown below:
//make func a function template
template<typename T, std::size_t N, std::size_t M>
void func(T (&arr)[N][M])
{
std::cout<<"func called with: "<<N<<" rows and "<<M<<" columns"<<std::endl;
}
int main()
{
int arr2[10][15];
func(arr2);
float arr3[3][4];
func(arr3);//this works too
return 0;
}
