简体   繁体   中英

How to pass array to function template with reference

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.

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.

The problem is in the return type: you cannot return an array because arrays are non-copiable. And by the way, you are returning nothing!

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 relevant line is the last one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM