You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将模板函数用于模板函子?解决std::pair排序编译报错问题

解决std::pair排序的模板函数编译错误

错误原因

你写的comp是模板函数,调用std::sort时直接传comp,编译器无法自动推导模板参数S——模板函数本身不是一个具体的函数实体,std::sort需要明确的函数类型,因此会报<unresolved overloaded function type>错误。

解决方案

方案1:显式指定模板参数

直接在调用时告诉编译器要实例化的模板参数类型:

typedef struct{
    int x, y;
} myStruct;

template <typename S> static bool comp(std::pair<int, S> pair1, std::pair<int, S> pair2){
    auto val1 = std::get<int>(pair1);
    auto val2 = std::get<int>(pair2);
    return val1 < val2;
}

int main(){
    myStruct test;
    std::vector<std::pair<int, myStruct>> v {{9,test}, {2,test}, {4,test}, {3,test}, {1,test}};
    std::sort(v.begin(), v.end(), comp<myStruct>); // 显式指定模板参数
}

方案2:用Lambda表达式(推荐,更简洁通用)

不需要单独写模板函数,直接在std::sort中定义Lambda,利用C++14的自动参数推导,适配任意类型的std::pair<int, S>:

typedef struct{
    int x, y;
} myStruct;

int main(){
    myStruct test;
    std::vector<std::pair<int, myStruct>> v {{9,test}, {2,test}, {4,test}, {3,test}, {1,test}};
    
    std::sort(v.begin(), v.end(), [](const auto& pair1, const auto& pair2) {
        return pair1.first < pair2.first; // 直接访问first成员更直观,比std::get更清晰
    });
}

这里用const auto&避免拷贝,效率更高,而且Lambda会被编译器自动推导类型,完美适配任意第二个元素类型的std::pair<int, S>。

方案3:使用函数对象(Functor)

如果需要复用比较逻辑,可以定义一个函数对象,模板会在使用时自动推导:

typedef struct{
    int x, y;
} myStruct;

template <typename S>
struct Comp {
    bool operator()(const std::pair<int, S>& pair1, const std::pair<int, S>& pair2) const {
        return pair1.first < pair2.first;
    }
};

int main(){
    myStruct test;
    std::vector<std::pair<int, myStruct>> v {{9,test}, {2,test}, {4,test}, {3,test}, {1,test}};
    std::sort(v.begin(), v.end(), Comp<myStruct>());
}

内容的提问来源于stack exchange,提问作者Pat cm pro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 00:10:43