C++:具有比较运算符重载的模板类
C++: template class with comparison 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 有效,但运算符重载不起作用?请注意,我想包括比较两种不同类型的三元组的可能性,因为例如,有人可能想将整数与双精度进行比较。我还尝试在类中实现比较函数,结果相同。
<<
的优先级高于==
。 这意味着您的表达式被解析为
(cout << asdf) == qwer;
只需添加括号即可解决此问题
cout << (asdf == qwer);
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用