How to pass an array to a function template with a link

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); } 

What am I trying?

1) T fun (T and x)

Here x is a reference and therefore will not decompose 'a' into a pointer type, but when compiling I get the following error.

  error: no matching function for call to 'fun(int [100])' 

When I try to use a link without a link, it works fine. As I understand it, the array decays into a pointer type.

+7
source share
2 answers

C-style masks are very simple constructs that cannot be assigned, copied, or referenced in the same way as built-in or custom types do. To get 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] ) { ... } 

Please note: here the size of the array is also a parameter of the template that allows functions to work, all sizes of the array, since T[M] and T[N] are not the same for different M , N Also note that the function returns void. There is no way to return an array by value, since the array cannot be copied, as already mentioned.

+16
source

The problem is with the return type: you cannot return an array because arrays are not copied. And by the way, you are not returning anything!

Try instead:

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

And it will work as expected.

NOTE. The original full error message (with gcc 4.8) is actually:

 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 

The most important line is the last.

+4
source

All Articles