我有一个模板类,有三种模板类型(基本上是一对还有一个成员),我无法让比较重载工作:
头:
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有效但操作员超载不起作用?请注意,我想要包括比较两种不同类型的三元组的可能性,例如,有人可能想要将双精度数据与双精度进行比较。我也尝试在类中实现具有相同结果的比较函数。
答案 0 :(得分:5)
<<
的优先级高于==
。这意味着您的表达式被解析为
(cout << asdf) == qwer;
只需添加括号即可解决此问题
cout << (asdf == qwer);