Search code examples
c++c++11templatesfunction-pointersfunction-templates

A code using pointer to function does not compile


I have used two templates in my code and a pointer to one of the template instantiate. But it doesn't compile. Can I know where is the problem?

template<typename T>
bool matcher(const T& v1, const T& v2)
{
    if (v1 == v2) return true;
    return false;
}

template<typename T1>
void compare(const T1* str1, const T1* str2, size_t size_m, bool(*)(const T1&, const T1&) func)
{
    for (size_t count{}; count < size_m; count++)
        if (func(str1[count], str2[count]))
            std::cout << "Mach at index of " << count << " is found\n";
}

int main()
{
    compare("888888", "98887", 4, &matcher<char>);
    return 0;
}

I know, I should be using std::function but I want to try this.


Solution

  • In the argument list of compare() function template, you have a typo in function pointer declaration. It should be

    void compare(const T1* str1, const T1* str2, size_t size_m, bool(*func)(const T1&, const T1&) )
    //                                                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    {
       // ... code
    }
    

    To make the function pointer type more (maybe)readable, you could provide a template type alias.

    template<typename T1>  // template alias type
    using FunctionPtrType = bool(*)(const T1&, const T1&);
    
    template<typename T1>
    void compare(const T1* str1, const T1* str2, size_t size_m, FunctionPtrType<T1> func)
    //                                                          ^^^^^^^^^^^^^^^^^^^^^^^^
    {
       // ... code
    }
    

    However, providing one more template parameter for the predicate would be less typing and less error-prone(IMO).

    template<typename T1, typename BinaryPredicate>
    void compare(const T1* str1, const T1* str2, size_t size_m, BinaryPredicate func)
    {
        // ... code
    }