Acorbe
Acorbe

Reputation: 8391

Overriding operator*() of iterators

Say that I have some user-defined complex struct, like

struct usrStruct{
     double a;
     T1 b;
     T2 c;
     /* and so on...*/
}

which is used as a basic element for a std::vector, std::list or anything iterable..

Say that the std::vector<usrStruct> is passed to a function of mine through iterators

  template<class InputIterator>  
  T myFoo( InputIterator first, InputIterator last ){ /*...*/ }.

Q: Is there a standard way to override operator*() of the InputIterator, (in this case of std::vector<usrStruct>::iterator ) so that myFoo just interacts with the member a?

i.e., so that

  *first == (*first).a;

and thus myFoo works orthogonally with respect to the whole definition of usrStruct?

Thank you.

Upvotes: 2

Views: 371

Answers (2)

BigBoss
BigBoss

Reputation: 6914

You can create a new iterator that based on vector::iterator and reflect it as double values and it is really simple:

template< class BaseIterator >
struct custom_iterator :
    std::iterator<std::iterate_traits<BaseIterator>::iterator_category, double>
{
public:
    typedef std::iterator<std::iterate_traits<BaseIterator>::iterator_category, double>
        base_t;
    typedef typename base_t::reference reference;
public:
    custom_iterator( BaseIterator it ) : m_it( it ) {}
public:
    reference operator*() const {
        return my_it->a;
    }
    custom_iterator& operator++ () {++m_it; return *this;}
    custom_iterator operator++ (int) {
        custom_iterator tmp( *this );
        ++m_it;
        return *this;
    }
    bool operator==( custom_iterator const& rhs ) const {
        return m_it == rhs.m_it;
    }
private:
    BaseIterator m_it;
};

And now you can use it as myFoo( custom_iterator(v.begin()), custom_iterator(v.end()) )

Upvotes: 2

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

No, you cannot do that. You can make your struct implicitly convertible to a double (via operator double). Or you can allow direct comparisons by overloading operator==(usrSruct,double) and/or operator==(double,usrStruct).

Upvotes: 1

Related Questions