【问题标题】:C++: template class with comparison operator overloadingC++:具有比较运算符重载的模板类
【发布时间】:2013-10-02 16:45:22
【问题描述】:

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

标题:

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 有效但运算符重载无效?请注意,我想包括比较两种不同类型的 Triples 的可能性,因为例如,有人可能想要比较 int 和 double。我还尝试在类中实现比较函数,结果相同。

【问题讨论】:

  • 顺便说一句,您应该尝试使用std::tuple 而不是为它创建自己的类。

标签: c++ templates operator-overloading


【解决方案1】:

&lt;&lt; 的优先级高于==。这意味着您的表达式被解析为

    (cout << asdf) == qwer;

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

   cout << (asdf == qwer);

【讨论】:

  • 愚蠢的我。如果编译器说“没有找到将 ostream 作为左侧操作数,将 Triple 作为右侧操作数的运算符”,我会立即知道。我责怪编译器。 :)
  • @SnowFatal 当我看到流式传输(&lt;&lt;&gt;&gt;)和其他运算符混合在一起并且无法编译时,这总是我的第一个想法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多