如何通过引用将数组传递给功能模板 [英] How to pass array to function template with reference
问题描述
我正在学习c ++模板概念。我不理解以下内容。
I am learning c++ template concepts. I do not understand the following.
#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);
}
我正在尝试什么?
1)T fun(T& x)
1) T fun (T & x)
这里x是一个引用,因此不会将'a'衰减为指针类型
但是在编译时,出现以下错误。
Here x is a reference, and hence will not decayed 'a' into pointer type, but while compiling , i am getting the following error.
error: no matching function for call to ‘fun(int [100])’
当我尝试非引用时,它可以正常工作。据我了解,数组被分解为指针类型。
When I try non-reference, it works fine. As I understand it the array is decayed into pointer type.
推荐答案
C样式数组是非常基本的构造,不能以内置或用户定义的方式进行分配,复制或引用类型是。要实现通过引用传递数组的等效功能,您需要以下语法:
C-style arrays are very basic constructs which are not assignable, copyable or referenceable in the way built-ins or user defined types are. To achieve the equivalent of passing an array by reference, you need the following syntax:
// 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] ) { ... }
请注意,这里的数组大小也是模板参数,允许函数使用所有数组大小,因为 T [M]
和 M
, N
,> T [N] 的类型不同。另请注意,该函数返回void。如前所述,由于数组不可复制,因此无法按值返回数组。
Note that here the size of the array is also a template parameter to allow the function to work will all array sizes, since T[M]
and T[N]
are not the same type for different M
, N
. Also note that the function returns void. There is no way of returning an array by value, since the array is not copyable, as already mentioned.
这篇关于如何通过引用将数组传递给功能模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!