没有匹配函数来调用"std::less:<int>:less(const int&, const int&)"

No matching function for call to ‘std::less<int>::less(const int&, const int&)’

本文关键字:int const less gt 函数 std lt 调用      更新时间:2023-10-16

我试着写:

#include <functional>
template<class T, class func = std::less<T>>
class Car {
public:
    void check(const T& x, const T& y) {
        func(x, y);            //.... << problem
    }
};

int main() {
    Car<int> car;
    car.check(6, 6);
    return 0;
}

我在这里的意思是,它会识别int的通常<,但它说的是我标记的地方:

调用"std::less::less(const int&,constint(amp;)'

但如果我用自定义func创建一个Car,那么它就可以工作。。。我该怎么解决?

您的问题是需要func的实例,因为std::less<T>是一个函子(即类类型),而不是函数类型。当你有

func(x, y);

实际上,您尝试使用xy作为构造函数的参数来构造一个未命名的std::less<T>。这就是为什么你得到

没有用于调用"std::less::less(const int&,const int&)"的匹配函数

因为CCD_ 10是构造函数调用。

你可以看到它是这样工作的:

#include <functional>
template<class T, class func = std::less<T>>
class Car {
    func f; 
public:
    void check(const int& x, const int& y) {
        f(x, y);
        // or
        func()(x, y); // thanks to Lightness Races in Orbit http://stackoverflow.com/users/560648/lightness-races-in-orbit
    }
};

int main() {
    Car<int> car;
    car.check(6, 6);
    return 0;
}

实时示例