Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ passing a pointer to a template function as template

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading