我有这个iter函数,它接受一个指向value_type、 a 的指针,以及一个应该接受 a作为参数的size_type函数指针:fun_typevalue_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]); }
Run Code Online (Sandbox Code Playgroud)
它工作得很好,直到我们有一个带有模板的函数,假设我们想使用这个函数:
template <
class T
> void print(const T &value) { std::cout << value << std::endl; }
Run Code Online (Sandbox Code Playgroud)
然后我们得到这个编译错误:
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)
Run Code Online (Sandbox Code Playgroud)
fun_type无论模板和函数的返回类型如何,我如何才能使用每个函数?
您的iter函数模板需要一个函数作为其第三个模板参数;但print(就其本身而言)不是一个函数 \xe2\x80\x93 它是一个函数模板,编译器根本无法推断出要使用什么模板参数才能实际创建一个函数 \xe2\x80\xa6 所以你需要告诉它!只需添加数组/指针的类型tab作为模板参数:
int main()\n{\n int tab[] = { 5,4,3,2,1 };\n iter(tab, 5, print<int>);\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
194 次 |
| 最近记录: |