C++ 模板函数问题与创建

C++ template function problem with concreating

我编写了带有 3 个参数的模板函数,T - 数组类型,FUNC - 函数 return 并获取 T 作为参数,N 作为数组大小。 我得到的编译错误几乎什么都没有告诉我:"Failed to specialize function template".

template<typename T,T* (*FUNC)(T), int N>
void process(T array[])
{
    for (int i=0;i<N;i++)
    {
        array[i] = FUNC(array[i]);
    }
}

int main()
{
    double a[] = { 1, 2, 3, 4 };
    process<double, sin, 4>(a); 
    for (auto x : a)
        std::cout << x << " "; // 0.841471 0.909297 0.14112 -0.756802
}

sin 与第二个模板参数不匹配。将函数声明更改为

template<typename T, T (*FUNC)(T), int N>
//                ^^ T, not T*