【问题标题】:Template type comparison in operator == overload运算符 == 重载中的模板类型比较
【发布时间】:2013-12-21 17:28:03
【问题描述】:

我为处理队列的类编写了运算符 == 的重载。 在这个类中,我使用了一个模板,我要添加的第一个控件是模板类型的控件。

这是代码

bool operator==(const Queue<T>& queue)
    {
        NodoCS<T>* NodoA = First;
        NodoCS<T>* NodoB = coda.First;

        if (this->DimQueue() != coda.DimQueue())
            return false;
        else
        {
            for (int i = 0; i < DimQueue(); i++)
            {
                if (NodoA->Element() != NodoB->Element())
                    return false;

                NodoA = NodoA->NextAddress();
                NodoB = NodoB->NextAddress();
            }

            return true;
        }
    }

示例: 我有这个队列:

Queue&lt;int&gt; queue1Queue&lt;string&gt; queue2

显然这些不相等,那么如何控制 int 与 string 不同?

我试过这样写函数的参数:

const Queue<T1>& queue

然后if(T != T1)....但这是错误的

【问题讨论】:

  • 如果函数参数中的模板类型TQueue的元素类型相同,你甚至无法编译queue1 == queue2
  • 您希望能够将Queue&lt;string&gt;Queue&lt;int&gt; amd 进行比较,如果是,为什么?

标签: c++ templates types queue operator-keyword


【解决方案1】:

只需编写operator== 的重载,它比较相同类型的队列,以及不同类型的队列。后者总是返回false

template<typename T>
bool operator==( const foo<T>& lhs , const foo<T>& rhs )
{
    return /* queues comparison */;
}

template<typename T , typename U>
bool operator==( const foo<T>& lhs , const foo<U>& rhs )
{
    return false;
}

Here 是 ideone 的一个运行示例。

【讨论】:

  • 在第一个中取消 SFINAE 和 U
  • @Yakk 那是真的,我把那件事复杂化了......谢谢:)
  • 当您遇到问题并认为“我可以通过 SFINAE 解决这个问题”时,现在您有两个问题。
  • 他要比较私有成员,这个非成员函数需要在Queue模板类中添加为好友吗?
  • @kwanti 没错,我个人总是将二元运算符定义为班级内的朋友;但这与问题无关。我这样写答案是因为代码更清晰。
【解决方案2】:

如果你使用的是 boost 或 c++11,

template<typename U>
typename std::enable_if<std::is_same<T, U>, bool>::type
operator == (const Queue<U>& other)
{
    ... do member comparison here
}

template<typename U>
typename std::disable_if<std::is_same<T, U>, bool>::type
operator == (const Queue<U>& other)
{
    return false;
}

【讨论】:

  • 好的,我有这个错误,我不知道如何处理它们:'Queue<:string>::First':无法访问在类中声明的私有成员' Queue<:string>' (字符串是第二种类型)...'!=' 二进制:没有找到任何接受 int 类型左操作数的运算符。
  • C++11 没有disable_if,只有 Boost 有。
  • @Manu343726 你是对的。我现在才意识到这一点。 :)
猜你喜欢
  • 1970-01-01
  • 2021-11-07
  • 2014-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多