我见过类似的问题,但还没有找到解决我的问题的方法,所以我希望能得到一些帮助。
我想将一个类作为参数传递给带有模板参数的函数(对于这个例子,我只是想让它编译,所以 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
)
您也必须实现该运算符或更改代码以使用提供的运算符。
关于C++ 模板与 operator< 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51212375/