如何使用模板通过比较课程?

问题描述 投票:0回答:1
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

ifstream cin("in.in");
ofstream cout("out.out");

template<typename Compare>
struct Info1 {
    int l;
    int r;
    bool operator<(Info1& a2) const {
        return Compare()(*this,a2);
    }
};

struct Comp1 {
    bool operator()(const Info1& a,const Info1& a2) const {
        return a.r<a2.r;
    }
};


int main() {
    
    vector<Info1<Comp1>> v1;
    return 0;
}

所以我尝试制作一个比较类 Comp1 然后将其传递给 Info1 的模板

在我看来这似乎没问题,但它不是这样编译的。

错误:

34:27: error: use of class template 'Info1' requires template arguments; argument deduction not allowed in function prototype
    bool operator()(const Info1& a,const Info1& a2) const {

你能帮帮我吗?

我试着运行那个代码

c++ templates lambda operators
1个回答
0
投票

问题

Info1
类模板而不是类类型

因此要解决这个问题,请将

Info1
替换为
Info1<T>
,如下所示。另请注意为重载添加的参数子句
operator()

struct Comp1 {
    //added this parameter clause
    template<typename T>     
    bool operator()(const Info1<T>& a,const Info1<T>& a2) const {
//-----------------------------^^^---------------^^^------------>added this to make it template-id
        return a.r<a2.r;
    }
};

工作演示

© www.soinside.com 2019 - 2024. All rights reserved.