Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I tried to write:

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

And my meaning here was that it will recognize the usual < for int, but it says where I marked:

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

But if I create a Car with customize func then it works... How Can I fix that?

like image 448
Stabilo Avatar asked Sep 11 '25 08:09

Stabilo


1 Answers

Your problem is that you need an instance of func since std::less<T> is a functor (i.e. class type) and not a function type. When you have

func(x, y);

You actually try to construct an unnamed std::less<T> with x and y as parameters to the constructor. That is why you get

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

as std::less::less(const int&, const int&) is a constructor call.

You can see it working like this:

#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

like image 188
NathanOliver Avatar answered Sep 12 '25 21:09

NathanOliver