2

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.

JeJo
  • 30,635
  • 6
  • 49
  • 88
asmmo
  • 6,922
  • 1
  • 11
  • 25
  • What's the error message? – Daniel H Dec 31 '19 at 06:48
  • 1
    I suspect `bool(*)(const T1&,const T1&) func` needs to be `bool(*func)(const T1&,const T1&)` in the argument list of `compare()`. – Peter Dec 31 '19 at 06:50
  • 2
    When a program does not compile, the first step is to check if the compiler provides an error message. – eerorika Dec 31 '19 at 06:53
  • 1
    To extend on the comment by @eerorika - the second step, when posting a question seeking help, is to actually provide the text of the error message. Where the error message mentions a line number (which is most often true in practice) ensure it is clear what line of code is being referred to. – Peter Dec 31 '19 at 06:57
  • 1
    *"I know, I should be using std::function"*: You do not want to [have the type erasure overhead](https://stackoverflow.com/questions/5057382/what-is-the-performance-overhead-of-stdfunction), without any reasons. – JeJo Dec 31 '19 at 07:12

1 Answers1

4

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
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • Using a templated predicate would demand even less typing if one was to spell "Binary" correctly. – Peter Dec 31 '19 at 06:58