简体   繁体   English

迭代器平等

[英]Iterator equality

I'm creating a container class which implements a double linked list. 我正在创建一个实现双链表的容器类。

template <class T>
class dl_list {
public:
    class link {
    public:
        T* data;
        link *prev, *next;
    };
    class iterator {
        link* node;
    public:
        link* get_node() { return node; }
        // ++, --, * operators, etc.
    };
    // other stuff
};

Pretty neat, I'm having fun with it. 非常整洁,我很开心。 But one problem I'm having is when I define my equality operators for the iterator type, I have to do a template specialization. 但是我遇到的一个问题是当我为迭代器类型定义我的相等运算符时,我必须进行模板特化。

template <class T>
bool operator==(typename dl_list<T>::iterator& lhv, typename dl_list<T>::iterator rhv) {
    return lhv.get_node() == rhv.get_node();
}

will not work, I have to specialize it like so: 不会工作,我必须像这样专门化:

bool operator==(typename dl_list<int>::iterator& lhv, typename dl_list<int>::iterator rhv) {
    return lhv.get_node() == rhv.get_node();
}

for every type I want to use it for, which is annoying for obvious reasons. 对于我想要使用它的每种类型,这显然是令人讨厌的原因。 How do I get around this? 我该如何解决这个问题?

Make it a member of the iterator class: 使它成为iterator类的成员:

bool operator==( const interator& other ) const
{
    return node == other.node;
}

You can't. 你不能。 The compiler cannot know that some T is a nested type of some other U . 编译器不能知道某些T是某些其他U的嵌套类型。 Consider 考虑

template<> class dl_list<float> {
public:
    typedef dl_list<int>::iterator iterator;
};

You have to take the iterator type directly as the template parameter, or define it as a member of the iterator class, or define the iterator class outside dl_list and simply make a typedef for it inside dl_list. 您必须直接将iterator类型作为模板参数,或者将其定义为迭代器类的成员,或者在dl_list之外定义迭代器类,并在dl_list中为它创建一个typedef。

Easiest cleanest way is to define the operator inside the iterator class: 最简单的方法是在迭代器类中定义运算符:

class iterator
{
  public:
    ...
    friend bool operator==(iterator& lhs, iterator& rhs)
    {
        return lhs.get_node() == rhs.get_node();
    }
};

(Bit of a code smell here - I'd have expected get_node() to have a const version, allowing the operator== to accept parameters by const reference...) (这里有一些代码味道 - 我希望get_node()有一个const版本,允许operator==通过const引用接受参数......)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM