【问题标题】:Generating member types for containers为容器生成成员类型
【发布时间】:2011-07-03 14:27:03
【问题描述】:

当我定义自己的容器时,我必须提供十几种成员类型,例如:

    typedef T& reference;
    typedef const T& const_reference;
    typedef T* iterator;
    typedef const T* const_iterator;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef T value_type;
    typedef T* pointer;
    typedef const T* const_pointer;
    typedef std::reverse_iterator<iterator> reverse_iterator;
    typedef std::reverse_iterator<const_iterator> const_reverse_iterator;

是否有我可以继承的基类模板,类似于 std::iterator&lt;T&gt; 用于我自己的迭代器?

【问题讨论】:

    标签: c++ stl containers base-class boilerplate


    【解决方案1】:

    如果你需要经常这样做,那么我想你可以创建一个

    template<typename T>
    struct container
    {
        typedef T& reference;
        typedef const T& const_reference;
        typedef std::size_t size_type;
        typedef std::ptrdiff_t difference_type;
        typedef T value_type;
        typedef T* pointer;
        typedef const T* const_pointer;
    };
    

    并由此继承。在标准库中,std::allocator 确实定义了所有这些 typedef,因此从它继承在技术上可以满足您的需求,并且不应强加任何运行时开销。不过,我仍然认为最好只编写自己的 typedef。

    【讨论】:

      【解决方案2】:

      有针对这个特定需求的 boost::iterator。

      我希望这个教程能让事情变得清晰http://www.boost.org/doc/libs/1_46_0/libs/iterator/doc/iterator_facade.html#tutorial-example

      【讨论】:

        【解决方案3】:

        是否有我可以继承的基类模板,类似于 std::iterator&lt;T&gt; 用于我自己的迭代器?

        不,但这是个好主意。 OTOH,这会使从容器中引用这些类型变得更加困难,因为它们将是基类中的标识符,依赖于派生类的模板参数。这可能会令人讨厌。

        【讨论】:

        • 对于“OTOH”部分:宏来救援!
        猜你喜欢
        • 1970-01-01
        • 2011-07-13
        • 2017-12-02
        • 1970-01-01
        • 2021-08-17
        • 1970-01-01
        • 1970-01-01
        • 2021-07-25
        • 1970-01-01
        相关资源
        最近更新 更多