我目前正在开发一个程序,我想将函数指针传递给自定义比较器的映射。然而,在以下最小的、可验证的示例中,这会产生错误:
#include <iostream>
#include <map>
struct CustomKey{
unsigned a;
};
bool compareCustom(const CustomKey &a, const CustomKey &b){
return a.a < b.a;
}
typedef decltype(compareCustom) CustomComparator;
int main(){
std::map<CustomKey, unsigned, CustomComparator> customMap(&compareCustom);
return 0;
}
使用 GCC 或 Clang 编译上述代码会产生过多的无信息模板错误,完全围绕 std::map
的内部实现。 This question似乎暗示传递函数指针类型是完全有效的。我的代码有什么问题?
最佳答案
传递一个函数指针是有效的,但传递一个函数是无效的。
typedef decltype(compareCustom) CustomComparator;
实际上使 CustomComparator
成为 bool(const CustomKey&, const CustomKey&)
类型,那是函数本身,而不是指针。
你应该使用:
typedef decltype(compareCustom) *CustomComparator;
关于c++ - 为什么我不能将函数指针作为模板参数传递给 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52685159/