C++ 将指针传递给模板函数作为模板

标签 c++ c++98

我有这个 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/

相关文章:

c++ - Visual Studio 2015 中的编译器是什么

c++ - 让代码更简洁

c++ - 在 gcc 中执行 C++98 标准

c++ - std::size_t 或 std::vector<Foo>::size_type?

c++ - 如何比较 std::map 中的所有项目?

c++ - "bitwise or"有时工作

c++ - 鉴于 myvector.start() 和 myvector.end() 我想创建 myvector 的只读子集而不复制数据。这可能吗?如何实现?

c++ - 如何修复 "Member is ambiguous"错误?

c++ - 删除 vector 和双端队列中项目的时间复杂度

c++ - boost asio 读缓冲区