我想寫一個函數,它會在控制檯上打印數據。該函數將被模板化,因爲它應該接受不同類型的數據。C++ 11 for循環在一個模板函數
的代碼如下所示:
template<typename DataType>
void PrintData(DataType *X)
{
for (DataType Data : X)
{
cout << Data << "\t";
}
cout << endl;
}
int main()
{
int nArray[7] = { 7, 5, 4, 3, 9, 8, 6 };
double dArray[5] = { 4.3, 2.5, -0.9, 100.2, 3.0 };
PrintData(nArray);
PrintData(dArray);
system("pause");
return EXIT_SUCCESS;
}
我得到一個錯誤可變數據是在模板函數PrintData未申報。
error C2065: 'Data' : undeclared identifier
error C3312: no callable 'begin' function found for type 'double *'
error C3312: no callable 'begin' function found for type 'int *'
error C3312: no callable 'end' function found for type 'double *'
error C3312: no callable 'end' function found for type 'int *'
任何幫助,將不勝感激。 謝謝
我敢肯定你的不僅僅是你所提到的一個得到了更多的錯誤。 –
'DataType *'不是數組或容器類型,循環範圍無法處理它。更重要的是,所寫的'PrintData'不知道'X'指向的元素的數量。如果你想要走這條路,可以把它設爲'template void PrintData(DataType(&X)[N]){...}'。 [Demo](http://rextester.com/XYYXJF94394) –
謝謝你的回答。我有其他疑問。 main()函數中的以下代碼是如何工作的: for(auto Data:nArray) cout << Data << endl; – Barry