C++ 模板与 operator< 不匹配

C++ Template no match for operator<

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

我想将 class 作为参数传递给带有模板参数的函数(对于这个例子,我只是想让它编译,所以 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

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

成员运算符总是使用左操作数作为 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;
}

因为您的 operator < 是一个成员函数,所以它期望左侧操作数是 class 类型。这对 low < *start 没问题,但在 *start < high 中你有一个 double 作为左手操作数。

您需要提供一个以双精度作为第一个参数的免费函数,或者使您的 class 可转换为双精度(或 T)。