数组的C++语法指针

use*_*112 2 c++ templates pointers const

在下面的:

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] << " ";
}
Run Code Online (Sandbox Code Playgroud)

我有点困惑为什么模板函数的函数签名没有通过使用[]来引用数组作为数组,所以类似于const T * const[] array.

怎么能从模板函数签名告诉数组正在传递而不仅仅是非数组变量?

jua*_*nza 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);
}
Run Code Online (Sandbox Code Playgroud)


Die*_*ühl 5

数组有一个大小.要创建对数组的引用,您需要静态提供大小.例如:

template <typename T, std::size_t Size>
void printArray(T const (&array)[Size]) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

此函数通过引用获取数组,您可以确定其大小.