C++ 模板与运算符<不匹配

C++ Template no match for operator<

本文关键字:lt 不匹配 运算符 C++      更新时间:2023-10-16

我见过类似的问题,但没有找到解决我问题的解决方案,所以我希望我能得到一些帮助。

我想将一个类作为参数传递给带有模板参数的函数(对于此示例,我只想编译它,因此 nvm 对运算符中的return true没有意义(。我认为在以下代码中以这种方式工作:

template<typename T>
class MyClass {
public:
bool operator>(const T&) const { 
return true;
}  
bool operator<(const T&) const { 
return true;
}
};
template<typename T, typename S> 
vector<T> between_interval(T* start, T* end, const S& low, const S& high){
vector<T> vec;
for ( ; start != end; start++) {
if (low < *start && *start < high)
vec.push_back(* start);
}
return vec;
}
int main() {
double v1[] = {1.23, 4.56, 7.89, -10, 4};
MyClass<double> k1;
MyClass<double> k2;
vector<double> res = between_interval(v1, v1 + 3, k1, k2);
for (auto x : res)
cout << x << " ";
cout << endl;
} 

我收到以下错误:

u4.cpp: In instantiation of ‘std::vector<T> between_interval(T*, T*, const S&, const S&) [with T = double; S = MyClass<double>]’:
u4.cpp:39:55:   required from here
u4.cpp:28:36: error: no match for ‘operator<’ (operand types are ‘double’ and ‘const MyClass<double>’)
if (low < *start && *start < high)

我意识到传递 K1 和 K2 目前没有意义,但编译器没有提到这一点,它抱怨没有匹配operator<,所以我的主要问题是为什么?operator<中的模板参数是否太笼统了?有没有其他方法可以让操作员工作但不使用模板?

谢谢

template<typename T>
class MyClass {
public:
bool operator>(const T&) const { 
return true;
}  
bool operator<(const T&) const { 
return true;
}
};

MyClass <double> k1;
double d = 4.2;

你可能会这样做

  • k1 < d
  • k1 > d

但你这样做

  • d < k1(带*start < high(

您还必须实现该运算符或更改代码以使用提供的运算符。

因为operator <是成员函数,所以它希望左手操作数是类类型。 这对low < *start来说很好,但在*start < high中,你有一个double作为左操作数。

您要么需要提供一个将双精度作为第一个参数的自由函数,要么使您的类可转换为双精度(或T(。

成员运算符始终使用左操作数作为this,使用右操作数作为运算符参数。这意味着您的比较运算符仅在MyClass位于比较左侧时才有效。快速解决方法是将行if (low < *start && *start < high)更改为if (low < *start && high > *start),以将MyClass实例放在每个比较的左侧。更清洁的解决方案是提供自由操作员,在左侧T,在右侧MyClass<T>。例如:

template<typename T>
bool operator>(const T& p_left, const MyClass<T> & p_right) {
return p_right < p_left;
}
template<typename T>
bool operator<(const T& p_left, const MyClass<T> & p_right) {
return p_right > p_left;
}