mardi 26 septembre 2017

How to implement standard iterators in class

I have classes which are usually using standard containers as underlying fields. For example, I have a class

template <typename T>
class Vec_3D
{
public:
    /* ... */
    std::array<T, 3> vec;
    /* ... */
};

which has only one variable vec and the rest are just functions I need when working with vectors. I want to be able to use range-based for loop such as

Vec_3D<double> vec;
for (double val : vec) {/*...*/}

which should obviusly iterate over std::array<double, 3>.

How to implement iterators in my class which should in turn call iterators of std::array<T, 3>?

I started with this question and tried to define iterators in my class as

typedef std::iterator<std::random_access_iterator_tag, T, ptrdiff_t, T*, T&> iterator;
typedef std::iterator<std::random_access_iterator_tag, const T, ptrdiff_t, const T*, const T&> const_iterator;

inline iterator begin() noexcept { return vec.begin(); }
inline const_iterator cbegin() const noexcept { return vec.cbegin(); }
inline iterator end() noexcept { return vec.end(); }
inline const_iterator cend() const noexcept { return vec.end(); }

but got compiling errors

error: no match for ‘operator!=’ (operand types are ‘Vec_3D<double>::iterator {aka std::iterator<std::random_access_iterator_tag, double, long int, double*, double&>}’ and ‘Vec_3D<double>::iterator {aka std::iterator<std::random_access_iterator_tag, double, long int, double*, double&>}’)

and operator++, operator*

Aucun commentaire:

Enregistrer un commentaire