Home > Blockchain >  How function templates can accept functions as parameters even thought functions are not types?
How function templates can accept functions as parameters even thought functions are not types?

Time:07-02

This obvious question might be asked somewhere which i couldn't found, the nearest answer is this . I come from a C background and if you want to pass a function as argument in C You ought to use a pointer to function . but this :


void    increment ( int & n ) { n  = 1; }

template <typename T, typename F>
void iterator(T *arr, size_t size, F f) {
    for (int i = 0; i < size; i  )
        f(arr[i]);
}

int main( void ) {
    int arr[] = {1, 2, 3, 4, 5};
    iterator(arr, 5, increment);
    return 0;
}

One answer (see link above) state that templated function can only accept either a type or a value !! Well function are not types, so what's the matter with typename F , the other possible option is that the function actually evaluate and return it's value to templated function parameter which definitely doesn't make sense, so my question. How exactly are functions can be passed as arguments to templated functions? what's going on behind the scenes ?

CodePudding user response:

Functions have a type. There is nothing fundamentally different from passing increment to the function template compared to passing arr. Their types get deduced and then replaced as the template arguments.

Perhaps it get clearer without argument deduction:

iterator<int, void()(int&)>(arr, 5, increment);

or letting decltype deduce the type:

iterator<int, decltype(increment)>(arr,5,increment);

If iterator wasnt a template it would look something like this (for this particular call):

using F = void(*)(int&);
void iterator(int* arr, size_t size, F f);
  • Related