Search code examples
c++templatesfunction-pointersstdvectorfunction-templates

How to pass a overloaded function pointer with a template data type?


In the below code I want to create a function count which counts the number of integers/strings which qualifies a match criteria from a vector of integers/strings.

But I am not clear about how to write the function definition.

#include <iostream>
#include <vector>
using namespace std;

bool match(int x) {
    return (x % 2 == 0);
}

bool match(string x) {
    return (x.length <= 3);
}

template <typename T>
int count(vector<T>& V, bool (*test)(<T>))
{
    int tally = 0;
    for (int i = 0; i < V.size(); i++) {
        if (test(V[i])) {
            tally++;
        }
    }
    return tally;
}

int main() 
{
    vector <int> nums;
    vector <string> counts;
    nums.push_back(2);
    nums.push_back(4);
    nums.push_back(3);
    nums.push_back(5);
    counts.push_back("one");
    counts.push_back("two");
    counts.push_back("three");
    counts.push_back("four");
    cout << count(nums, match) << endl;
    cout << count(counts, match) << endl;
}

How should the prototype be written ? I realize the error is at the line

int count (vector<T> &V , bool (*test)(<T>) ) 

Solution

  • The function pointer type is

    <return-type>(*function-pointer-identifier)(<argument-types>)<other specifiers>
    

    Meaning, you need to remove the extra <> from the count function and you are good to go.

    template <typename T>
    int count(std::vector<T>& V, bool (*test)(T))
    //                           ^^^^^^^^^^^^^^^^^
    

    Or you could provide a template type alias for the function pointer type, which might make simpler to read

    template <typename T>
    using FunPtrType = bool (*)(T); // template alias
    
    template <typename T>
    int count(std::vector<T>& V, FunPtrType<T> test)
    {
       // ...
    }
    

    (See a demo)


    Side notes