以下内容:
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
这样的东西。
如何从模板函数签名中判断出数组正在传递而不仅仅是非数组变量??
答案 0 :(得分:9)
你无法确定。您必须阅读文档和/或从函数参数的名称中找出它。但是,由于您正在处理固定大小的数组,您可以将其编码为:
#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);
}
答案 1 :(得分:5)
数组有一个大小。要创建对数组的引用,您需要静态提供大小。例如:
template <typename T, std::size_t Size>
void printArray(T const (&array)[Size]) {
...
}
此函数通过引用获取数组,您可以确定其大小。
答案 2 :(得分:0)
您可以尝试以下内容:
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。