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

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

发生了什么事?

最佳答案

错误是您提供了模板的部分特化。作品决定一切或一无所有。因此,如果您按如下方式更改签名:

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

...

reduce(sum, data, 0.0, 5)

一切顺利

关于c++ - 函数指针作为模板参数,类型推导失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15931247/

相关文章:

c++ - scanf(), std::cin 在多线程环境下如何表现?

C++ 等同于 Python 的 doctests?

C++ 和 IBM 编译器错误?

c++ - GetDIBits() 因 PNG 压缩而失败

c++ - 确保 C++ 类具有某些成员函数

c++ - 类型名和标量常量的可变参数模板

使用夹具的 C++ GoogleTest - 函数指针定义不可访问

Python ctypes 函数指针

c++ - 如何使指针指向非成员函数?

c++ - 为什么我的结果数据返回为 void* 损坏?