如何通过引用将数组传递给函数模板

Who*_*ami 8 c++

我正在学习c ++模板概念.我不明白以下几点.

#include <iostream>
#include <typeinfo>

using namespace std;

template <typename T>
T fun(T& x)
{
 cout <<" X is "<<x;
 cout <<"Type id is "<<typeid(x).name()<<endl;
}


int main ( int argc, char ** argv)
{
   int a[100];
   fun (a);
}
Run Code Online (Sandbox Code Playgroud)

我在尝试什么?

1)T fun(T&x)

这里x是一个引用,因此不会将'a'衰减为指针类型,但在编译时,我收到以下错误.

 error: no matching function for call to ‘fun(int [100])’
Run Code Online (Sandbox Code Playgroud)

当我尝试非引用时,它工作正常.据我所知,数组被衰减为指针类型.

jua*_*nza 23

C风格的数组是非常基本的结构,它们不像内置函数或用户定义的类型那样可赋值,可复制或可引用.要实现相当于通过引用传递数组,您需要以下语法:

// non-const version
template <typename T, size_t N>
void fun( T (&x)[N] ) { ... }

// const version
template <typename T, size_t N>
void fun( const T (&x)[N] ) { ... }
Run Code Online (Sandbox Code Playgroud)

请注意,这里的数组的大小也是一个模板参数,使功能起作用将所有数组的大小,因为T[M]T[N]是不是同一类型的不同M,N.另请注意,该函数返回void.没有办法按值返回数组,因为数组不可复制,如前所述.


rod*_*igo 6

问题出在返回类型:您无法返回数组,因为数组是不可复制的.顺便说一下,你什么都没回来!

尝试改为:

template <typename T>
void fun(T& x)  // <--- note the void
{
    cout <<" X is "<<x;
    cout <<"Type id is "<<typeid(x).name()<<endl;
}
Run Code Online (Sandbox Code Playgroud)

它将按预期工作.

注意:原始的完整错误消息(使用gcc 4.8)实际上是:

test.cpp: In function ‘int main(int, char**)’:
test.cpp:17:10: error: no matching function for call to ‘fun(int [100])’
    fun (a);
      ^
test.cpp:17:10: note: candidate is:
test.cpp:7:3: note: template<class T> T fun(T&)
 T fun(T& x)
   ^
test.cpp:7:3: note:   template argument deduction/substitution failed:
test.cpp: In substitution of ‘template<class T> T fun(T&) [with T = int [100]]’:
test.cpp:17:10:   required from here
test.cpp:7:3: error: function returning an array
Run Code Online (Sandbox Code Playgroud)

最相关的一行是最后一行.