【问题标题】:iterating over container of objects from an inheritance hierarchy while hiding pointers从继承层次结构中迭代对象容器,同时隐藏指针
【发布时间】:2019-01-31 15:50:15
【问题描述】:

我遇到的问题如下:我有一个对象的继承层次结构,并且我想定义一个类,该类表示该层次结构中可以具有不同动态类型的对象集合。我想知道是否有一种方法可以制作和迭代这样的集合,同时隐藏它包含指针的事实。目前我的代码可以总结如下:

class Base{
    public:
       virtual Base* clone() const & { return new Base(*this); }
       virtual Base* clone() && { return new Base( std::move(*this) ); }
    ... other members ...

};

class Derived : public Base{
    public: 
        Derived* clone() const & override { return new Derived(*this); }
        Derived* clone() && override { return new Derived( std::move(*this) ); }
    ... other members ...
};

class ObjectCollection{
    public:
        ... constructor and other members...

        // use 'clone' function to initialize the collection without having to pass pointers
        void push_back( const Base& );
        void push_back( Base&& );

        using iterator = std::vector< std::shared_ptr< Base > >::iterator
        using const_iterator = std::vector< std::shared_ptr< Base > >::const_iterator

        iterator begin(){ return collection.begin(); }
        const_iterator begin() const{ return collection.cbegin(); }

        iterator end() { return collection.end(); }
        const_iterator end() const{ return collection.cend(); }
    private: 
        std::vector< std::shared_ptr< Base > > collection;
};

//loop over objects:
ObjectCollection collection(...call to constructor...);
for( auto & object : collection ){
    //object is now a reference to shared_ptr to Object rather than a reference to Object!
}

理想情况下,我希望能够像上一个那样编写一个 for 循环,在其中我可以直接获取对对象的引用,而不是指针。有没有办法做到这一点?还是继续使用指针会更好? (注意:我知道的解决问题的一种方法,但我想避免,是重载 [] 运算符以取消引用指针)。

【问题讨论】:

  • 滚动你自己的迭代器来包装底层迭代器,但为你解引用。

标签: c++ pointers inheritance containers dynamic-binding


【解决方案1】:

使用range-v3,您可以创建shared_ptr 集合的参考视图:

auto get_collection_view() /*const*/
{
    return collection | ranges::v3::transform([](auto&& p) -> /*const*/ Base& { return *p; });
}

【讨论】:

    猜你喜欢
    • 2011-08-10
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 2015-03-26
    • 2014-12-22
    • 1970-01-01
    • 2023-03-28
    • 2023-03-13
    相关资源
    最近更新 更多