我正在阅读 C++ Templates Complete Guide 并遇到了这个非类型函数模板参数代码(我添加了 main() 和除函数定义和调用之外的其他部分):
#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;
}
从书中阅读后我不明白为什么我们需要对函数调用进行类型转换?
编辑:书中的解释:
add 是一个函数模板,函数模板被认为是命名一组重载函数(即使该集合只有一个成员)。但是,按照目前的标准,重载函数集不能用于模板参数推导。因此,您必须转换为函数模板参数的确切类型:...
编译器:Ubuntu 10.10 上的 g++ 4.5.1