使用模板将数组作为参考作为参数传递

Passing array as a reference as a parameter using template

因为我不知道数组的大小,所以我使用 size 作为参数传递到我的函数中。

这个有效:

#include <cstddef>
#include <iostream>

template<class T, size_t N>
void takeArrayParam(T (&myArray)[N]) {
    for(auto i = std::begin(myArray); i != std::end(myArray); i++) {
        std::cout << *i << std::endl;
    }
}

int main() {
    int coolArray[10] = {1,2,3,4,5,6,7,8,9,10};
    takeArrayParam<int, 10>(coolArray);
    return 0;
}

这不起作用(编译器错误):

#include <cstddef>
#include <iostream>

template<class T, size_t N>
void takeArrayParam(T (&myArray)[N]) {
    for(auto i = std::begin(myArray); i != std::end(myArray); i++) {
        std::cout << *i << std::endl;
    }
}

int main() {
    size_t size = 10;
    int coolArray[size];
    //int coolArray[10] = {1,2,3,4,5,6,7,8,9,10};
    takeArrayParam<int, size>(coolArray);
    return 0;
}

差异:coolArray[10]coolArray[size]

谢谢...

您需要将 const 添加到 main() 中的 size 定义中。
那是因为在堆栈上分配的数组的大小需要在编译时知道。

问题是 size 不是 constant expression 在编译时已知 ),在你的情况下使用 const 声明它或者 constexpr 可以解决您的问题:

constexpr size_t size = 10;

在这种情况下使用 const 是可行的,因为您使用文字 10 进行初始化,这是一个 常量表达式 。这包含在 C++ 标准草案 5.19 expr.const 中,它说:

A conditional-expression is a core constant expression unless it involves one of the following as a potentially evaluated subexpression

并包括以下项目符号:

an lvalue-to-rvalue conversion (4.1) unless it is applied to

  • a glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression, or

注意数组大小也必须是常量表达式:

int coolArray[size];
              ^^^^

正如我在对 Does “int size = 10;” yield a constant expression? several compilers support variable length arrays(VLA) 的回答中所述,它是 C99 的一个功能,作为 C++ 的扩展,但它不可移植,特别是 Visual Studio 不支持 VLA。