在stl容器包装中定义迭代器类型 [英] Define an iterator type in a stl container wrapper

查看:108
本文介绍了在stl容器包装中定义迭代器类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

围绕STL容器(也是模板)(可以接受泛型T作为元素)编写包装器类的正确方法是什么,它允许我像直接使用STL容器那样使用迭代器?

What it the right way to write a wrapper class around an STL container, which is also a template (can accept a generic type T as element) and allows me to use an iterator as I would do with the STL container directly?

我想做以下类型的事情

#include <list>
#include <iostream>

class MyClass{};

template<class T>
class Wrapper
{
    public:
        typename std::list<T>::iterator iterator;

        std::list<T> elements;
        iterator begin(){ return elements.begin(); };
        iterator end(){ return elements.end(); };
};

int main()
{
    Wrapper<MyClass> wrapper;

    for (Wrapper::iterator it = wrapper.begin(); it != wrapper.end(); ++it)
        std::cout<<"Hi"<<std::endl;
}

但是编译器说:

 error: ‘iterator’ in ‘class Wrapper<T>’ does not name a type


推荐答案

您有两个错误。

就像Igor Tandetnik在评论中说的那样,您的 iterator 是数据成员,而不是案例的嵌套类型。

Like Igor Tandetnik said in a comment, your iterator is a data member, not a nested type of your case.

您必须在课堂上这样做:

You have to do this in your class:

typedef typename std::list<T>::iterator iterator;

或在C ++ 11中:

or, in C++11:

using iterator = typename std::list<T>::iterator;

此外,您使用的是 iterator 错误 main()代码中的方式。应该是这样的:

Also, you are using iterator the wrong way in your main() code. It should be like this:

Wrapper<MyClass>::iterator it = wrapper.begin()

或者,在C ++ 11或更高版本中,您可以这样做:

Or, in C++ 11 or later, you can do this:

for(const auto &element : wrapper) {
    ...
}

就个人而言,我宁愿使用私有继承而不是封装。在我看来,公共继承意味着 IS A关系,而私人继承则意味着 IS IPLEMENTED IN TERM OF关系。

Personally, I would prefer to use private inheritance instead of encapsulation. In my head, public inheritance means an "IS A" relationship, whereas private inheritance means an "IS IMPLEMENTED IN TERM OF" relationship.

您可以这样做:

template<typename T>
class WrapperList : private List<T> {
    ... Your code that belongs to your wrapper
}

这篇关于在stl容器包装中定义迭代器类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆