为什么我不能将函数指针作为模板参数传递给地图?

Why can't I pass a function pointer as a template parameter to a map?

我目前正在开发一个程序,我想将函数指针传递给自定义比较器的映射。然而,在以下最小的、可验证的示例中,这会产生错误:

#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;