2012-11-30 24 views
1

我有大意如下的一类通用转换迭代:定义为遍历不同的容器类型

class ArraySim{ 

    public: 
    DataStructure* ds; 
    ArraySim(bool which){ 
     if(true) 
      ds = new STDMap(); 
     else 
      ds = new HashMap(); 
    } 
    value_type& operator[](int idx){ 
      return ds->getValAtIndex(idx); 
    } 

    //define a custom iterator type that can be used to iterate over both std::map and boost::unordered //map keys. 
} 

class DataStructure{ 

    vitrual value_type& getValAtIndex(int idx)=0; 
}; 

class STDMap: public DataStructure{ 
    //Class that wraps a std::map object and implements the virtual method to return the value against a //particular index(key) 
}; 

class HashMap: publlic DataStructure{ 
    //Class that wraps a boost::unordered_map object and implements the virtual method to return the value //against a particular index(key) 
} 

我已通过:Generic IteratorTransform Iterator。据我所知,转换迭代器仍然要求您在模板参数中提供底层容器迭代器。那么是否有一种方法可以使用变换迭代器来定义映射键周围的自定义迭代器类型,并同时使其适用于不同类型的映射容器?

+1

可以删除的类型,如升压:: any_iterator做(从http://www.boost.org/ DOC /库/ 1_52_0 /库/范围/ DOC/HTML /范围/参考/范围/ any_range.html)。 –

回答

1

如果您使用的是Boost,则可以使用any_range

typedef any_range<value_type, boost::forward_pass_traversal_tag, 
    value_type &, std::ptrdiff_t> range; 
typedef any_range<value_type, boost::forward_pass_traversal_tag, 
    const value_type &, std::ptrdiff_t> const_range; 
typedef range::iterator iterator; 
typedef const_range::const_iterator const_iterator; 

virtual iterator begin() = 0; 
virtual iterator end() = 0; 
virtual const_iterator begin() const = 0; 
virtual const_iterator end() const = 0; 

beginend虚函数只需要构建合适的迭代器:

iterator begin() { return iterator(object.begin()); } 
+0

请注意,您*不希望“reference”类型为“value_type”,而是'value_type&'。此外,这不能正确地适应'const'范围。 – Xeo

+0

@Xeo欢呼声,修好了。 – ecatmur

+0

由于'value_type const&'不能转换为'value_type&'(提示:你需要两个typedef),所以'const'范围仍然不能正常工作。 – Xeo