关于非类型模版形参——数组为什么要以引用传值
函数里并没有改变数组里的值,为什么一定要用引用?
代码如下:
#include <iostream>非类型模版形参 数组
#include <string>
#include <vector>
using namespace std;
template <class T, size_t N>
size_t size( T (&arr)[N] ) // 为什么要用引用
{
return N;
}
template <class T, size_t N>
void printValues( const T (&arr)[N] ) // 为什么要用引用
{
for ( size_t i = 0; i != N; ++i )
{
cout << arr[ i ] << endl;
}
}
int main()
{
int a[] = { 1, 2, 3, 4 };
int length = size( a );
printValues( a );
return 0;
}
template< typename T, size_t N >
void fun( T ( *p )[N] )
{
std::cout << ( *p )[1] << std::endl;
}
int main()
{
int a[ 10 ] = { 100, 200, 300 };
double b[ ] = { 50.24, 60.32, 70.99 };
fun( &a );
fun( &b );
return 0;
}
这里完全可以用指针。
[解决办法]