11

我正在学习 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])’

当我尝试非参考时,它工作正常。据我了解,数组已衰减为指针类型。

4

2 回答 2

30

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。如前所述,由于数组不可复制,因此无法按值返回数组。

于 2013-05-12T08:08:12.877 回答
6

问题在于返回类型:你不能返回一个数组,因为数组是不可复制的。顺便说一句,你什么都没有回来!

请尝试:

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

它会按预期工作。

注意:原始的完整错误消息(使用 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

最相关的行是最后一行。

于 2013-05-12T08:29:44.367 回答