我试图使用函数指针作为非类型模板参数,但有时我不明白为什么它无法推断出类型。
这里有一个例子
template <class T, class U, class R>
R sum(T a, U b) { return a + b; }
template <class T, class R, R (*Func)(T, R)>
R reduce(T *in, R initial, int len) {
for (int i = 0; i < len; ++i)
initial = Func(in[i], initial);
return initial;
}
int main() {
double data[] = {1, 2, 3, 4, 5};
std::cout << "Sum: " << reduce<sum>(data, 0.0, 5) << "\n";
return 0;
}
不幸的是,GCC 似乎没有提供失败的原因:
test.cpp: In function ‘int main()’:
test.cpp:15:64: error: no matching function for call to ‘reduce(double [5], double, int)’
test.cpp:15:64: note: candidate is:
test.cpp:7:3: note: template<class T, class R, R (* Func)(T, R)> R reduce(T*, R, int)
test.cpp:7:3: note: template argument deduction/substitution failed:
相反,指定所有数据类型将使其工作:
std::cout << "Sum: " << reduce<double, double, sum>(data, 0.0, 5) << "\n";
怎么了?