我有这个 iter
函数,它接受一个指向 value_type
的指针、一个 size_type
和一个函数指针 fun_type
> 应该采用 value_type&
作为参数:
template <
class value_type,
class size_type,
class fun_type
> void iter(value_type *arr, size_type size, fun_type function)
{ while (size--) function(arr[size]); }
它工作得很好,直到我们有一个带有模板的函数,比方说我们想使用这个函数:
template <
class T
> void print(const T &value) { std::cout << value << std::endl; }
然后我们得到这个编译错误:
main.cpp:35:1: error: no matching function for call to 'iter'
iter( tab, 5, print );
^~~~
./iter.hpp:17:8: note: candidate template ignored: couldn't infer template argument 'fun_type'
> void iter(value_type *arr, size_type size, fun_type function)
^
main.cpp:36:1: error: no matching function for call to 'iter'
iter( tab2, 5, print );
^~~~
./iter.hpp:17:8: note: candidate template ignored: couldn't infer template argument 'fun_type'
> void iter(value_type *arr, size_type size, fun_type function)
如何使 fun_type
适用于每个函数,无论模板和函数的返回类型如何?
最佳答案
您的 iter
函数模板需要一个函数作为其第三个模板参数;但是 print
(就其本身而言)不是一个函数 - 它是一个函数模板,并且编译器根本无法推断出要使用的模板参数为了实际创建一个函数......所以你需要告诉它!只需添加 tab
数组/指针的类型作为模板参数:
int main()
{
int tab[] = { 5,4,3,2,1 };
iter(tab, 5, print<int>);
return 0;
}
关于C++ 将指针传递给模板函数作为模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71084193/