[英]C++ syntax pointer for array
在下面的:
int c[10] = {1,2,3,4,5,6,7,8,9,0};
printArray(c, 10);
template< typename T >
void printArray(const T * const array, int count)
{
for(int i=0; i< count; i++)
cout << array[i] << " ";
}
我有點困惑為什么模板函數的函數簽名沒有通過使用[]來引用數組作為數組,所以像const T * const[] array
這樣的東西。
怎么能從模板函數簽名告訴數組正在傳遞而不僅僅是非數組變量?
你無法確定。 您必須閱讀文檔和/或從函數參數的名稱中找出它。 但是,由於您正在處理固定大小的數組,您可以將其編碼為:
#include <cstddef> // for std::size_t
template< typename T, std::size_t N >
void printArray(const T (&array)[N])
{
for(std::size_t i=0; i< N; i++)
cout << array[i] << " ";
}
int main()
{
int c[] = {1,2,3,4,5,6,7,8,9,0}; // size is inferred from initializer list
printArray(c);
}
數組有一個大小。 要創建對數組的引用,您需要靜態提供大小。 例如:
template <typename T, std::size_t Size>
void printArray(T const (&array)[Size]) {
...
}
此函數通過引用獲取數組,您可以確定其大小。
您可以嘗試以下內容:
template< std::size_t N>
struct ArrayType
{
typedef int IntType[N];
};
ArrayType<10>::IntType content = {1,2,3,4,5,6,7,8,9,0};
template< std::size_t N >
void printArray(const typename ArrayType<N>::IntType & array)
{
//for from 0 to N with an array
}
void printArray(const int * & array)
{
//not an array
}
Raxvan。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.