代码之家  ›  专栏  ›  技术社区  ›  john01dav

为什么我不能将函数指针作为tempalte参数传递给映射?

  •  0
  • john01dav  · 技术社区  · 6 年前

    我目前正在开发一个程序,我想为自定义比较器传递一个指向映射的函数指针。但是,在以下最低限度的verifable示例中,这会产生错误:

    #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 似乎表明传递函数指针类型是完全有效的。我的代码有什么问题?

    1 回复  |  直到 4 年前
        1
  •  3
  •   llllllllll    6 年前

    typedef decltype(compareCustom) CustomComparator;
    

    实际上使 CustomComparator 类型 bool(const CustomKey&, const CustomKey&) ,这是函数本身,而不是指针。

    您应该使用:

    typedef decltype(compareCustom) *CustomComparator;