函数指针作为模板参数,类型推导失败

时间:2013-04-10 16:20:21

标签: c++ templates function-pointers

我试图将函数指针用作非类型模板参数,但有时我不明白为什么它不能推断出类型。

这是一个例子

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";

发生了什么事?

1 个答案:

答案 0 :(得分:2)

您提供模板部分特化的错误。全部或全无规则。因此,如果您更改签名如下:

template <class T, class R>
 R reduce(R (*Func)(T, R), T *in, R initial, int len) {

...

reduce(sum, data, 0.0, 5)

一切都编好了

相关问题