Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用指向函数的指针的代码不会编译_C++_C++11_Templates_Function Pointers_Function Templates - Fatal编程技术网

C++ 使用指向函数的指针的代码不会编译

C++ 使用指向函数的指针的代码不会编译,c++,c++11,templates,function-pointers,function-templates,C++,C++11,Templates,Function Pointers,Function Templates,我在代码中使用了两个模板和一个指向其中一个模板实例化的指针。但它没有编译。 我能知道问题出在哪里吗 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,

我在代码中使用了两个模板和一个指向其中一个模板实例化的指针。但它没有编译。 我能知道问题出在哪里吗

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;
}
我知道,我应该使用std::function,但我想试试这个。

在比较函数模板的参数列表中,函数指针声明有一个输入错误。应该是

void compare(const T1* str1, const T1* str2, size_t size_m, bool(*func)(const T1&, const T1&) )
//                                                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
   // ... code
}
为了使函数指针类型更容易接受,可以提供模板类型别名

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
}
但是,为谓词再提供一个模板参数将减少键入和错误概率

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

错误消息是什么?我怀疑在compare的参数列表中bool*const T1&,const T1&func需要是bool*funconst T1&,const T1&。当程序未编译时,第一步是检查编译器是否提供错误消息。要扩展@eerorika的注释,第二步是在发布寻求帮助的问题时,实际上是提供错误消息的文本。如果错误消息提到一个行号,这在实践中通常是正确的,请确保清楚引用的是哪一行代码。我知道,我应该使用std::function:您不想这样做,没有任何原因。如果要正确拼写二进制,使用模板谓词将需要更少的键入。