C++ 模板与运算符<不匹配
C++ Template no match for operator<
我见过类似的问题,但没有找到解决我问题的解决方案,所以我希望我能得到一些帮助。
我想将一个类作为参数传递给带有模板参数的函数(对于此示例,我只想编译它,因此 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;
}
相关文章:
- Qt SQLite没有查询或参数计数不匹配
- 模板参数推导失败,函数参数/参数不匹配
- 在使用累加时,C++中的运算符+不匹配
- C++ 与操作员不匹配<<
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 与'operator='不匹配(操作数类型'String'且"void")
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- C4018:类内有符号、无符号不匹配
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 为什么我收到错误:"运算符<<不匹配?
- RE2 不匹配非 ASCII 字符
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 模板推导:为什么函数指针模板定义在常量和/或引用时不匹配?
- 错误:"模板<类_Tp,类_Dp>类 std::unique_ptr"的模板参数列表中参数 1 的类型/值不匹配
- OpenSSL fips in C++ wrapper Library 如何?错误:指纹不匹配
- 为什么我的数组值与此处的全局变量不匹配?
- 引号之间匹配/不匹配,带有不可避免的引号和多行
- 映射迭代器与运算符不匹配
- C++调用和定义不匹配
- 模板专用化与派生类不匹配