Home > front end >  How to pass a template function as an argument in C ?
How to pass a template function as an argument in C ?

Time:12-23

Consider this for a second:

template <class T_arr, class T_func>
void iter(T_arr *arr, int len, T_func func)
{
    for(int i = 0; i < len; i  )
    {
        func(arr[i]);
    }
}

void display(int a) {
    std::cout << "Hello, your number is: " << a << std::endl;
}

int main(void)
{    
    int arr[] = {1, 2, 3};

    iter(arr, 3, display);
    return (0);
}

Which works as expected, however, if I try to change the display function to a template:

template <class T>
void display(T a) {
    std::cout << "Hello, your number is: " << a << std::endl;
}

It stops working and i get this error: candidate template ignored: couldn't infer template argument 'T_func'.

How to make sense of this?

CodePudding user response:

You need to specify the template argument for display explicitly:

iter(arr, 3, display<int>);

Or make iter taking function pointer:

template <class T_arr>
void iter(T_arr *arr, int len, void (*func)(T_arr))
{
    for(int i = 0; i < len; i  )
    {
        func(arr[i]);
    }
}

then you can

iter(arr, 3, display); // template argument gets deduced as int
  • Related