我正在学习 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);
}
我在做什么?
1) T 乐趣 (T & x)
这里的 x 是一个引用,因此不会将 'a' 衰减为指针类型, 但是在编译时,出现以下错误。
error: no matching function for call to ‘fun(int [100])’
当我尝试非引用时,它工作正常。据我了解,数组已衰减为指针类型。
最佳答案
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] ) { ... }
请注意,这里数组的大小也是一个模板参数,以允许函数在所有数组大小下工作,因为 T[M]
和 T[N]
对于不同的M
,N
不是同一类型。另请注意,该函数返回 void。无法按值返回数组,因为数组不可复制,如前所述。
关于c++ - 如何通过引用将数组传递给函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16505376/