#include <iostream>
template <typename T>
inline
T accum (T const* beg, T const* end)
{
T total = T(); // assume T() actually creates a zero value
while (beg != end) {
total += *beg;
++beg;
}
return total;
}
int main()
{
// create array of 5 integer values
int num[]={1,2,3,4,5};
// print average value
std::cout << "the average value of the integer values is "
<< accum(&num[0], &num[5]) / 5
<< '\n';
// create array of character values
char name[] = "templates";
int length = sizeof(name)-1;
// (try to) print average character value
std::cout << "the average value of the characters in \""
<< name << "\" is "
<< accum(&name[0], &name[length]) / length
//<< accum<int>(&name[0], &name[length]) / length //but this give me error
<< '\n';
}
我正在阅读 c++ 模板:完整的指南,作者提到我可以使用模板专业化
accum<int>(&name[0], &name[length]) / length
我在 Visual Studio 2012 中尝试这个并得到错误
main.cpp(34): error C2664: 'accum' : cannot convert parameter 1 from ' char *' to 'const int *'
我的 C++ 有点生疏了。
我只是好奇,如果这种“行为”以前允许,但“最新”C++ 标准发生了变化,使其非法,或者这是我正在阅读的书中的错误。