允许在C ++中访问容器对象 [英] Allowing access to container objects in C++

查看:121
本文介绍了允许在C ++中访问容器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类如下:

class Foo {
private:
    std::map<std::string, Bar*> bars_by_name;
    std::map<std::string, Baz*> bazs_by_name;
};

现在我想允许用户访问这两个集合, m将对象存储到std :: maps中。相反,我想有成员函数返回例如。 const迭代器,甚至可能是一个定制的迭代器,从两个集合返回对象,因为Bar和Baz属于同一个类层次结构。考虑到样式,在C ++中这样做的正确方法是什么?在Java中,我可能将方法的返回类型设置为Iterable或将集合包装到一个unmodifiableCollection中。

Now I'd like to allow the user to access both collections but hide the implementation detail that I'm storing the objects into std::maps. Instead, I'd like to have member functions that return e.g. const iterators for the collections and possibly even a custom iterator that returns objects from both collections, since Bar and Baz belong to the same class hierarchy. Considering style, what would be the proper way to do this in C++? In Java, I'd probably set the method's return type to Iterable or wrap the collection into an unmodifiableCollection.

推荐答案

class Foo {
  private:
    typedef std::map<std::string, Bar*> BarContainer;
    typedef std::map<std::string, Baz*> BazContainer;
  public:
    typedef BarContainer::const_iterator ConstBarIterator;
    ConstBarIterator beginBars() { return bars_by_name.cbegin(); }
    ConstBarIterator endBars()   { return bars_by_name.cend(); }
    typedef BazContainer::const_iterator ConstBazIterator;
    ConstBazIterator beginBazs() { return bazs_by_name.cbegin(); }
    ConstBazIterator endBazs()   { return bazs_by_name.cend(); }

  private:
    BarContainer bars_by_name;
    BazContainer bazs_by_name;
};

这节省了您实现自己的迭代器的工作,

This saves you the work of implementing your own iterator, yet leaves you the flexibility of changing your container types later and only requiring callers to recompile.

它不能解决将它们重复在一起的问题。

It doesn't solve the problem of iterating them both together.

这篇关于允许在C ++中访问容器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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