在以下内容中:
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);
}
关于数组的 C++ 语法指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13810259/