[英]Function pointer as template argument, type deduction failing
我试图将函数指针用作非类型模板参数,但有时我不明白为什么它无法推断类型。
这是一个例子
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";
怎么了?
您提供模板的部分专业化的错误。 一切皆有可能。 因此,如果您按照以下方式更改签名:
template <class T, class R>
R reduce(R (*Func)(T, R), T *in, R initial, int len) {
...
reduce(sum, data, 0.0, 5)
一切都编译良好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.