C++ 模板与 operator< 不匹配

标签 c++ templates operators operator-keyword

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

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

相关文章:

c++ - 并行执行的 OpenCL 验证

templates - Scala 模板设置变量

C++ 模板没有匹配的函数调用

mysql - 检查最近更新时间是否大于10分钟

c++ - 在 C++ 中,我需要创建一个程序,当输入某个数字时循环并停止,然后显示最大值和最小值

c++ - 在 C++ 中确定对象类型

c++ - 在运行的 Windows 控制台应用程序中处理拖放文件

c++ - 在不同的文件中模板化模板实例化

c - 运算符优先级和演变

c - 使用 mod 运算符 c 的问题