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?
Your problem is that you need an instance of func
since std::less<T>
is a functor (ie 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.