简体   繁体   中英

How to pass a template function as an argument in C++?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM