通过引用传递给模板函数

Lea*_*Lea 7 c++ arrays templates

我有找到max的功能,我想通过引用发送静态数组,为什么这不可能?

template <class T>
T findMax(const T &arr, int size){...}

int main{
  int arr[] = {1,2,3,4,5};
  findMax(arr, 5); // I cannot send it this way, why?
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*ain 7

使用正确的语法.将签名更改为:

template <class T, size_t size>
T findMax(const T (&arr)[size]){...}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用std::array参数进行findMax()功能.

实例

为什么这不可能?

const T &arr:这arr是类型的引用,T而不是T您可能认为的类型数组的引用.所以你需要[..]之后arr.但是它会腐烂到一个指针.在这里你可以改变绑定()和使用const T (&arr)[SIZE].

更多信息,您可以尝试探索const T &arr[N]v/s 之间的差异const T (&arr)[N].