Home > other >  c passing a pointer to a template function as template
c passing a pointer to a template function as template

Time:02-12

I have this iter function that takes a pointer to value_type, a size_type, and a function pointer fun_type that is supposed to take a value_type& as parameter:

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]); }

It works fine until we have a function that has a template, let's say for example we want to use this function:

template <
   class T
> void print(const T &value) { std::cout << value << std::endl; }

Then we get this compilation error:

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)

How could I make fun_type work with every function no matter the template and the return type of the function?

CodePudding user response:

Your iter function template requires a function for its third template parameter; but print (on its own) is not a function – it's a function template, and the compiler simply cannot deduce what template parameter to use in order to actually create a function … so you need to tell it! Just add the type of the tab array/pointer as that template parameter:

int main()
{
    int tab[] = { 5,4,3,2,1 };
    iter(tab, 5, print<int>);
    return 0;
}
  • Related