c++ - 为什么我不能将函数指针作为模板参数传递给 map ?

标签 c++ templates stl function-pointers

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

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

相关文章:

c++ - 有没有人在 C++/WinAPI 中有类似 FileSystemWatcher 的类?

c++ - 可以自由地使用涉及类模板参数推导的函数样式转换表达式吗?

c++ - 如何使用函数指针定义多重集?

c++ - 无法创建模板 vector 迭代器

c++ - Qt 所见即所得 - 字体大小问题

c++ - 填充插入() - 复制构造函数和复制赋值 noexcept 状态?

C++ 模板 - 在元组及其类型的容器上进行模板化

c++ - 从模板函数返回 double 或 complex<double>

opengl - 如何在 STL 算法中使用 glm 的 operator==?

c++ - 这个 C++ 片段的语法是什么?