C++:具有比较运算符重载的模板类

标签 c++ templates operator-overloading

我有一个包含三种模板类型的模板类(基本上是一对,还有一个成员),但我无法使比较重载工作:

标题:

template<typename FirstType, typename SecondType, typename ThirdType>
class Triple
{
public:
    Triple(FirstType f, SecondType s, ThirdType t) : var1(f), var2(s), var3(t)
    {}
...
private:
    FirstType var1;
    SecondType var2;
    ThirdType var3;
};


template<typename F1, typename S1, typename T1, typename F2, typename S2, typename T2>
bool operator==(const Triple<F1,S1,T1>& one, const Triple<F2,S2,T2>& other)
{
    return true; //just for testing
}


template<typename F1, typename S1, typename T1, typename F2, typename S2, typename T2>
bool testFunc(const Triple<F1,S1,T1>& one, const Triple<F2,S2,T2>& other)
{
    return true; //just for testing
}

主要内容:

Triple<int, int, int> asdf(1, 1, 2);
Triple<int, int, int> qwer(1, 21, 2);
cout << asfd == qwer;         //doesn't work
cout << testFunc(asfd, qwer); //works

我收到以下有关 == 运算符的错误消息:

binary '==' : no operator found which takes a right-hand operand of type 'Triple<FirstType,SecondType,ThirdType>'

为什么 testFunc 有效而运算符重载却无效?请注意,我想包括比较两种不同类型的三元组的可能性,因为例如有人可能想比较整数和 double 。我还尝试在类中实现比较函数,结果相同。

最佳答案

<<优先级高于 == .这意味着您的表达式被解析为

    (cout << asdf) == qwer;

只需添加括号即可解决此问题

   cout << (asdf == qwer);

关于C++:具有比较运算符重载的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19142279/

相关文章:

c++ - 如何将模板类容器的迭代器传递给函数?

c++ - 为数组重载运算符<<

c++ - 有什么方法可以将 cookie 传递给 IWebBrowser2 导航

c++ - 不能从 doxygen 的输入中排除文件

c++ - 有没有办法继承别名模板?

c++ - 关于重载运算符的问题 <<

c++ - << 运算符重载返回 std::string 时出错

c++ - MPI 和全局对象 : All ranks have the object at same memory address?

c++ - 如何将毫秒添加到纪元以来的持续时间?

c++ - 无法将模板参数 NULL 转换为 void*