我在看<>时遇到的一个关于函数模板的问题!
kiro 2004-03-04 11:27:05 我在看<< C++ Primer >> 的模板实例化中遇到了这样一个问题。
书中有这么一段程序:
#include <iostream>
using namespace std;
template <typename Type, int size>
Type min(Type (&r_array)[size])
{
Type min_val = r_array[0];
for (int i = 1; i < size; i++)
if (r_array[i] < min_val)
min_val = r_array[i];
return min_val;
}
int ia[5] = {10, 7, 14, 3, 25};
double da[6] = {10.2, 7.1, 14.5, 3.2, 25.0, 16.8};
int main()
{
int i = min(ia);
if (i != 3)
cout << "??oops: integer min() failed\n";
else cout << "!!ok: integer min() worked\n";
double d = min(da);
if (d != 3.2)
cout << "??oops: double min() failed\n";
else cout << "!!ok: double min() worked\n";
return 0;
}
我在VC中编译通不过以下是它的错误信息
//===========================================================
: error C2265: '<Unknown>' : reference to a zero-sized array is illegal
: error C2784: 'Type __cdecl min(Type (&)[1])' : could not deduce template argument for ' (&)[1]' from 'int [5]'
: error C2784: 'Type __cdecl min(Type (&)[1])' : could not deduce template argument for ' (&)[1]' from 'double [6]'
Error executing cl.exe.
=============================================================
我想请教各位有没有人能够帮忙修改一下这段程序,要求既能通过编译又能遵循原作者的意图
谢谢!