我正在嘗試將任意大小的二維陣列傳遞給函式。我嘗試過的代碼如下:
#include <iostream>
void func(int (&arr)[5][6])
{
std::cout<<"func called"<<std::endl;
}
int main()
{
int arr[5][6];
func(arr);
return 0;
}
如您所見,func正確呼叫了。但我想傳遞任何大小的二維陣列。在當前示例中,我們只能通過int [5][6].
PS:我知道我也可以使用,vector但我想知道是否有辦法用陣列來做到這一點。例如,我應該能夠寫:
int arr2[10][15];
func(arr2);//this should work
uj5u.com熱心網友回復:
您可以使用模板來做到這一點。特別是,使用如下所示的非型別模板引數:
#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;
}
在上面的例子中N和M被稱為非型別模板引數。
使用模板我們甚至可以使陣列中元素的型別任意,如下所示:
//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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/406658.html
標籤:
下一篇:來自int的強型別列舉。C 11
