#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';
}
I was reading c++ templates:the complete guide book and the author mentioned
that I can use template specialization
accum<int>(&name[0], &name[length]) / length
I try this in visual studio 2012 and got error
main.cpp(34): error C2664: ‘accum’ : cannot convert parameter 1 from ‘char *’ to ‘const int *’
My C++ is a bit rusty.
I’m just curious, if this “behavior” previously allowed but there’s changes in “latest” C++ standard making this illegal or this is an error on the book I’m reading.
The instantiation is
int accum<int> (int const* beg, int const* end), you can’t passchar *arguments to this function.The reason the uncommented line works is that it instantiates
accum<char>.