Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass array to function template with reference

Tags:

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

What i am trying?

1) T fun (T & x)

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.

like image 213
Whoami Avatar asked May 12 '13 08:05

Whoami


1 Answers

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] ) { ... }

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.

like image 142
juanchopanza Avatar answered Sep 29 '22 11:09

juanchopanza