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

时间:2016-01-07 20:46:31

标签: c++ class templates

我试着写:

#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&amp;,const        INT&安培)”

但是,如果我使用自定义Car创建func,那么它可以正常工作......我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

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

func(x, y);

您实际上尝试使用std::less<T>x构建一个未命名的y作为构造函数的参数。这就是你得到的原因

  

没有匹配函数来调用'std :: less :: less(const int&amp;,const int&amp;)'

因为std::less::less(const int&, const int&)是构造函数调用。

你可以看到它像这样工作:

#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;
}

Live Example

相关问题