I am reading C++ Templates Complete Guide and came across this non-type function template parameters code (I have added the main() and other parts except the function definition and call):
#include <vector>
#include <algorithm>
#include <iostream>
template <typename T, int value>
T add (T const & element){
return element + value;
}
int main() {
int a[] = {1,2,3,4};
int length = sizeof (a) / sizeof (*a);
int b[length];
std::transform (a, a + length, b, (int(*)(int const &))add <int, 5>); //why?
std::for_each (b, b + length, [](int const & value){ std::cout << value << '\n'; });
return 0;
}
I did not understand after reading from the book why we need typecasting of the function call?
EDIT: Explaination from the book:
add is a function template, and function templates are considered to name a set of overloaded functions (even if the set has only one member). However, according to the current standard, sets of overloaded functions cannot be used for template parameter deduction. Thus, you have to cast to the exact type of the function template argument:...
Compiler: g++ 4.5.1 on Ubuntu 10.10